简体   繁体   English

为什么在没有单击按钮的情况下加载页面时会触发我的脚本功能?

[英]Why is my script function being fired when the page loads without a button click?

I'm trying to use JQuery's on() function to attach an event to a button and any button that will be dynamically created and injected later on. 我正在尝试使用JQuery的on()函数将事件附加到按钮以及稍后将动态创建和注入的任何按钮。 However, when I run the test website, it calls alertMe() without clicking the button. 但是,当我运行测试网站时,它无需单击按钮即可调用alertMe()。 alertMe is in a .js file and of course, I have the JQuery file. alertMe在.js文件中,当然我还有JQuery文件。 This is about as simple an example as I can create - am I missing something here with attaching this event with JQuery? 这是我可以创建的一个简单示例-我是否在通过JQuery附加此事件时丢失了某些内容?

<body>
    <script src="Scripts/JScript.js" type="text/javascript"></script>
    <script src="Scripts/jquery.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('button').on("click", alertMe());
        });
    </script>
    <form id="form1" runat="server">
    <div id="1">
        <button data-attr="1">
            Say Sumfin'</button>
    </div>
    </form>
</body>

data-attr is just a custom attribute that I'll use to identify the buttons I'll be attaching this too. data-attr只是一个自定义属性,我将使用它来标识将要附加的按钮。

EDIT 编辑

So the reason the question was asked will remain evident, I've left it as-is. 因此,提出该问题的原因仍然很明显,我将其保持原样。 But this is what I used to actually have the event properly attach to dynamically added elements. 但这就是我以前实际将事件正确附加到动态添加的元素的方式。

$(document).on('click', '[data-attr]', alertMe);

This: 这个:

$( 'button' ).on( 'click', alertMe );

The .on() method expects a function reference as its second argument. .on()方法期望将函数引用作为第二个参数。 Notice the difference: 注意区别:

alertMe // function reference

alertMe() // function invocation

Because you're putting parentheses after the function name! 因为您要在函数名称后加上括号! That means, "call this function". 这意味着“调用此功能”。

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

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