Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

asp.net - using a href to call javascript function with parameter

I'm trying to call javascript function from a href . the function has a parameter which will be retrieved by the eval function . But some error occurs .

script:

function rate(id) {

            // do something
        }

the a tag that will call the function:

<a href="javascript:rate(" + <%#Eval("ID")%> + ")" >rate</a>

What am I missing ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You shouldn't be doing it like this, but the issue you're currently up against is probably is your quoting/concatenating.

If <%#Eval("ID")%> simply produces an INT, this should work:

<a href="javascript:rate( <%#Eval("ID")%> )" >rate</a>

If it's a string,

<a href="javascript:rate( '<%#Eval("ID")%>' )" >rate</a>

should do it for you, although you need to handle the case of <%#Eval("ID")%> producing anything with a single quote in it.

A Lesson:

I say you shouldn't be doing it like this because the javascript pseudo protocol (javascript:) is defunct and improper. At worst you should be using an onclick which returns false. Ideally you'd be assigning the event programatically and preventing the event object's default action.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...