简体   繁体   English

调用 onclick 覆盖的函数不起作用

[英]Call onclick an overrided function doesn't work

I have difficulty with a certain code right now.我现在对某些代码有困难。 I tried to look on Internet and other StackOverflow, but none seems to work for me...我试图查看 Internet 和其他 StackOverflow,但似乎没有一个适合我...

I have a function (defined in a code that doesn't belongs to me and that I can't change manually) which I am trying to override correctly.我有一个函数(在不属于我的代码中定义,我无法手动更改),我试图正确覆盖它。 For each click of a certain button, it should call the new overrided function, but it doesn't work.对于某个按钮的每次单击,它应该调用新的覆盖函数,但它不起作用。 It always call the first version of it.它总是调用它的第一个版本。

In fact, I can't change the order of the code below unfortunately.事实上,不幸的是我不能改变下面代码的顺序。

<script>
$('button').click(select_options);

function select_options(){
     // some TO DO here
}
</script>

In another file that I can change, I did:在另一个我可以更改的文件中,我做了:

<script>
window.select_options = function() {
      // I redefine the function here as what I want
}
</script>

When I click on a button, it calls the first definition of function "select_options".当我点击一个按钮时,它会调用函数“select_options”的第一个定义。 How can I fix and override correctly the function which it will be called by a click of the user on buttons?我怎样才能正确修复和覆盖用户单击按钮时将调用的函数?

You will need to unbind this specific event handler and rebind new one.您将需要取消绑定这个特定的事件处理程序并重新绑定新的。 You of course need to be careful and not to remove other handlers.您当然需要小心,不要删除其他处理程序。 You sould do it like this for example:你应该这样做,例如:

$('button').off('click', select_options).on('click', function () {
  console.log('B')
})

Here is a demo of how it preserves other handlers:这是它如何保留其他处理程序的演示:

 $('button').click(select_options).click(function () { console.log('other handler') }) function select_options() { console.log('A') // Remove original select_options and bind version B $('button').off('click', select_options).on('click', function () { console.log('B') }) }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button>Test</button>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM