使用 href 调用带参数的 javascript 函数
我正在尝试从 href 调用 javascript 函数。该函数有一个参数,该参数将由 eval 函数检索。但出现一些错误。
script:
function rate(id) {
// do something
}
将调用函数的 a 标签:
<a href="javascript:rate(" + <%#Eval("ID")%> + ")" >rate</a>
我缺少什么?
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不应该这样做,但您当前遇到的问题可能是您的引用/连接。
如果
<%#Eval("ID")%>
只是生成一个 INT,那么这应该可以工作:如果它是一个字符串,
应该为您执行此操作,尽管您需要处理 < 的情况code><%#Eval("ID")%> 生成任何带有单引号的内容。
教训:
我说你不应该这样做,因为 javascript 伪协议 (
javascript:
) 已经失效并且不正确。最坏的情况下,您应该使用返回 false 的onclick
。理想情况下,您将以编程方式分配事件并阻止事件对象的默认操作。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:If it's a string,
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 anonclick
which returns false. Ideally you'd be assigning the event programatically and preventing the event object's default action.我认为根本没有必要使用 eval() 。像这样的引号中的代码是在顶级范围内评估的。如果您确保在该顶级范围内定义了速率和 ID,那么它将在没有 eval() 的情况下使用此 HTML:
和此代码:
您可以在此处看到它的工作原理: http://jsfiddle.net/jfriend00/bqqpM/。在没有 eval 的情况下完成这项工作的技巧只是确保 ID 和速率在顶级范围内都可用。
I don't see any need for the use of eval() at all. Code in quotes like this is evaluated at the top level scope. If you make sure that both rate and ID are defined at that top level scope, then it will work without eval() with this HTML:
and this code:
You can see it work here: http://jsfiddle.net/jfriend00/bqqpM/. The trick to making this work without eval is just making sure that ID and rate are both available at the top level scope.
您不应该使用
" + + "
,因为它只会被替换为数字:You shouldn't use
" + + "
, because it will just be replaced with a number:为什么将其称为 href?您只需制作一个按钮并将其样式设置为链接即可。那会容易很多
Why call it as an href? You can just make a button and style it like a link. That would be a lot easier