Javascript jQuery attr('onclick')
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5781616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery attr('onclick')
提问by Shark
I'am trying to change "onclick" attribute in jQuery but it doesn't change, here is my code:
我正在尝试更改 jQuery 中的“onclick”属性,但它没有改变,这是我的代码:
$('#stop').click(function() {
$('next').attr('onclick','stopMoving()');
}
I have an element with id="stop" and when user clicks on it I want to change an onclick attribute on element which has id="next".
我有一个 id="stop" 的元素,当用户点击它时,我想更改 id="next" 元素的 onclick 属性。
If someone knows where is the solution please help!
如果有人知道解决方案在哪里,请帮助!
回答by Felix Kling
Do it the jQuery way (and fix the errors):
以 jQuery 方式执行(并修复错误):
$('#stop').click(function() {
$('#next').click(stopMoving);
// ^-- missing #
}); // <-- missing );
If the element already has a click
handler attached via the onclick
attribute, you have to remove it:
如果元素已经click
通过onclick
属性附加了处理程序,则必须将其删除:
$('#next').attr('onclick', '');
Update:As @Drackir pointed out, you might also have to call $('#next').unbind('click');
in order to remove other click handlers attached via jQuery.
更新:正如@Drackir 指出的那样,您可能还需要调用$('#next').unbind('click');
以删除通过 jQuery 附加的其他点击处理程序。
But this is guessing here. As always: More information => better answers.
但这是在这里猜测。一如既往:更多信息 => 更好的答案。
回答by Tim
As @Richard pointed out above, the onClick needs to have a capital 'C'.
正如@Richard 上面指出的,onClick 需要有一个大写的“C”。
$('#stop').click(function() {
$('next').attr('onClick','stopMoving()');
}
回答by Artnik
The easyest way is to change .attr() function to a javascript function .setAttribute()
最简单的方法是将 .attr() 函数更改为 javascript 函数 .setAttribute()
$('#stop').click(function() {
$('next')[0].setAttribute('onclick','stopMoving()');
}
回答by fgallego
Try with this version jquery-1.10.2!
试试这个版本的 jquery-1.10.2!
回答by Ryan Sullivan
Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use
Felix Kling 的方法行得通,(实际上打我一拳),但我也打算建议使用
$('#next').die().live('click', stopMoving);
$('#next').die().live('click', stopMoving);
this might be a better way to do it if you run into problems and strange behaviors when the element is clicked multiple times.
如果多次单击元素时遇到问题和奇怪的行为,这可能是一种更好的方法。