javascript 按钮 onclick 到 click() jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5463109/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 17:17:08  来源:igfitidea点击:

Button onclick to click() jquery

javascriptjquerybutton

提问by nils

I have a button that reacts to onclick() at the moment, but I want it to work with jquery.

我现在有一个对 onclick() 做出反应的按钮,但我希​​望它可以与 jquery 一起使用。

$('#nupp1').click(function() {
    raiseButtonAction(realPlayer, gameState);
});

raisebuttonaction is in another .js This piece of code isn't working. Am I doing something wrong? edit1:

raisebuttonaction 在另一个 .js 中 这段代码不起作用。难道我做错了什么?编辑1:

$(document).ready(function() {
    $('#nupp1').click(function() {
        raiseButtonAction(realPlayer, gameState);
    });
});

回答by BrunoLM

Assuming you have this:

假设你有这个:

<head>
    <scripts />
</head>
<body>
    <a id="nupp1"></a>
</body>

You code will not work. jQuery will not be able to find the element. The element must exists for that function to work. So

你的代码将不起作用。jQuery 将无法找到该元素。该元素必须存在才能使该功能正常工作。所以

<a id="nupp1"></a>
<script />

Will work because ais being rendered before the script.

将工作,因为a在脚本之前呈现。

You can also use $(document).readyor $()to execute your function when the DOM nodes load.

您还可以在 DOM 节点加载时使用$(document).ready$()来执行您的函数。

Or you can use jQuery.live.

或者你可以使用jQuery.live.

jQuery API

jQuery API

  • readySpecify a function to execute when the DOM is fully loaded.
  • liveAttach a handler to the event for all elements which match the current selector, now and in the future.
  • ready指定在 DOM 完全加载时要执行的函数。
  • live将处理程序附加到与当前选择器匹配的所有元素的事件,现在和将来。