jQuery attr('onclick')

2019-01-23 01:52发布

I'am trying to change "onclick" attribute in jQuery but it doesn't change, here is my code:

$('#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".

If someone knows where is the solution please help!

5条回答
Emotional °昔
2楼-- · 2019-01-23 02:20

Try with this version jquery-1.10.2!

查看更多
等我变得足够好
3楼-- · 2019-01-23 02:26

Felix Kling's way will work, (actually beat me to the punch), but I was also going to suggest to use

$('#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.

查看更多
太酷不给撩
4楼-- · 2019-01-23 02:31

The easyest way is to change .attr() function to a javascript function .setAttribute()

$('#stop').click(function() {
    $('next')[0].setAttribute('onclick','stopMoving()');
}
查看更多
三岁会撩人
5楼-- · 2019-01-23 02:38

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}
查看更多
乱世女痞
6楼-- · 2019-01-23 02:40

Do it the jQuery way (and fix the errors):

$('#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:

$('#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.

But this is guessing here. As always: More information => better answers.

查看更多
登录 后发表回答