javascript jQuery 事件未触发

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

jQuery event not firing

javascriptjqueryjsonhyperlink

提问by Sindhu13

I have 3 files:

我有3个文件:

  • js_json.js -> for my json code
  • javascript.js -> for my javascript function
  • index.php
  • js_json.js -> 用于我的 json 代码
  • javascript.js -> 用于我的 javascript 函数
  • 索引.php

Here the code for js_json.js:

这里的代码js_json.js

$(function(){
    $('#postTitle').change(function(){

        var title_id = $("#postTitle").val();


        $.ajax({
            type:"post",
            url:"proses.php",
            data:"title_id=" + title_id,
            dataType:"json",
            success:function(data){
                body="";
                //$.each(data, function(i,n){
                    //body = n['body'];    
                //});
                body += "<a href=\"javascript:void(0);\" id=\"pesan\" name="pesan" onClick=\"\">Hola Test</a>";
                $(".postBody").empty();
                $(".postBody").append(body);
            },
            error:function(data){
                $(".postBody").empty();
                $(".postBody").append("NO Post Selected.");
            }

        });
        return false;
    });
});

and here my javascript.jscode:

这里是我的javascript.js代码:

$(function (){
    $("a[name=pesan]").click(function (){
        alert("holalalalalal.....!");    
    });
});

and here the index.phpcode:

和这里的index.php代码:

    //some code
    <body>
        <a href="javascript:void(0);" id="pesan" name="pesan">Hola Test 1</a>
        Posts : <br />
        <select name="title" id="postTitle">
            <option value="">Select Post...</option>
            <?php
                $sql = "SELECT id, title FROM posts ORDER BY title";
                $query = mysql_query($sql) or die(mysql_error());

                while($rows = mysql_fetch_array($query)){
                    print('<option value="' . $rows['id'] . '">' . $rows['title'] . '</option>');
                }
            ?>
        </select>
        <br />
        Body : <br />
        <div class="postBody">
            Will show the body of post.
        </div>
    </body>
</html>

and my question is:

我的问题是:

When I click the link "Hola Test 1", it works and the message appears. The problem is, after I click the select option, and the link "Hola Test" appears, and then I click that ("Hola Test") link, the message does not appear and there are no errors in firebug...

当我单击“Hola Test 1”链接时,它可以工作并显示消息。问题是,在我单击选择选项并出现链接“Hola 测试”后,然后单击该(“Hola 测试”)链接,该消息没有出现,并且萤火虫中没有错误...

Can somebody explain to me why...? Thank's...

有人可以向我解释为什么...?谢谢...

回答by Matt

click()will only bind the event for elements that exist in the page at the time clickis called (the same goes for on()without a selector, bind(), and all the other methods in the shortcut-group for bind; keydown(), change()etc. ).

click()将仅绑定,当时存在于页面元素事件click被调用(这同样适用on(),而不选择器,bind()和快捷组用于结合在所有其他方法; keydown()change()等)。

Because your other element is getting added via AJAX some time later, the handler isn't bound for it.

由于您的其他元素稍后通过 AJAX 添加,因此处理程序并未绑定到它。

Use .on()with a selector instead, which will bind the event to all current and future elements matched by the selector.

.on()与选择器一起使用,它将事件绑定到选择器匹配的所有当前和未来元素。

$(function (){
    $(document).on('click', 'a[name=pesan]', function () {
        alert("holalalalalal.....!");    
    });
});

Since on()was introduced in jQuery 1.7, if you're using earlier versions of jQuery (like those that existed when this question was asked), you can use live()or delegate()instead of on;

由于on()是在 jQuery 1.7 中引入的,如果您使用的是 jQuery 的早期版本(就像问这个问题时存在的那些),您可以使用live()ordelegate()代替 on;

$(function (){
    $('a[name=pesan]').live('click', function () {
        alert("holalalalalal.....!");    
    });
});

回答by HostileFork says dont trust SE

I want to mention (because I found no mention of it in any of the "event not firing" cases I scoured the web for)that there is a possibility which might bite you.

我想提一下(因为我在网上搜索的任何“事件未触发”案例中都没有提到它)有可能会咬你。

If you happen to use .remove()to extract something temporarily from the DOM and then reinsert it, then you will lose your events. What you need to use instead is .detach()to preserve the data and events after reinsertion. This can be hard to debug as everything may look normal, and the event debugging tools are sketchy at best.

如果您碰巧使用.remove()从 DOM 中临时提取某些内容然后重新插入它,那么您将丢失事件。您需要使用的是.detach()来在重新插入后保留数据和事件。这可能很难调试,因为一切看起来都很正常,而且事件调试工具充其量只是粗略的。

(Personally I would call them something more like .detachAndScrubDataAndEvents()and .detach(), as I'm a fan of descriptive names saving hours of debugging. For those who find .remove()and .detach()to be semantically and meaningfully distinguished names... peace be with you... BUT you're flat out wrong.)

(我个人会打电话给他们更多的东西一样.detachAndScrubDataAndEvents().detach() ,因为我是描述性的名称保存调试小时的粉丝。对于那些谁找到一个.remove().detach()在语义上和有意义的杰出名字......与你同在......但你完全错了。)