简体   繁体   English

用jQuery插入后的按钮操作不起作用

[英]button action after insert with jquery not working

i have an button "add" i click it then a save button will append to my div. 我有一个按钮“添加”,我单击它,然后一个保存按钮将追加到我的div。 this is working, but i cant trigger the function of the "save" button. 这是可行的,但我无法触发“保存”按钮的功能。 if i paste the "save"- button in the code directly it is working. 如果我直接将“保存”-按钮粘贴到代码中,则它可以正常工作。 i cant find my error... 我找不到我的错误...

<a class="save" href="#"><img src="images/save.png" alt="save_working" /></a>
<a class="add_row" href="#"><img src="images/icon_add_light.png" alt="add" /></a><br>
<div id="hinzu"></div>


$(".save").click(function() {
    alert("saveworking");
});


$(".add_row").click(function() {
    $("#hinzu").append('  <a class="save" href="#"><img src="images/save.png" alt="savenotworking" /></a>');
});

Here is an fiddle with it: http://jsfiddle.net/MgcDU/321/ 这是一个小提琴: http : //jsfiddle.net/MgcDU/321/

Why isnt this working with the js append method? 为什么不使用js append方法呢?

It's dynamic, so it does not exist when you're binding the event. 它是动态的,因此绑定事件时不存在。 For that you would need to delegate the event to an element that actually exists at the time of attaching the event handler : 为此,您需要将事件委托给附加事件处理程序时实际存在的元素:

$("#hinzu").on('click', '.save', function() {
    alert("saveworking");
});

Use it like: 像这样使用它:

$("#hinzu").on('click', ".save", function() {
    alert("saveworking");
});

this is because when you try to do the $(".save") it does not exist. 这是因为当您尝试执行$(“。save”)时,它不存在。

You have to use the on() for monitoring if any new .save are in your doom and assign the event handler. 您必须使用on()来监视是否有任何新的.save在您的厄运中并分配事件处理程序。

$("#hinzu").on('click', '.save', function()
{
    alert("This Does work");
});

It is not working because the $(".save").click() call binds the onclick handler to all elements with class save which already existed at the point of the call. 它不起作用,因为$(".save").click()调用将onclick处理程序绑定到在调用时已经存在的所有具有save类的元素。

To bind the event handler also to elements which did not exist at the time of the binding, you must use $(document).on('click', '.save', function() { [...] }) 要将事件处理程序也绑定到绑定时不存在的元素,必须使用$(document).on('click', '.save', function() { [...] })

If you want to save you code, use this: 如果要保存代码,请使用以下命令:

<script type="text/javascript">
    $(function() {
        $('.save').click(function() {
            alert('saveworking');
        });
    });

    $(function() {
        $('.add_row').click(function() {
            alert('add_row');
        });
    });
</script>

One more way to do this: 执行此操作的另一种方法:

<script type="text/javascript">
    $(document).ready(function () {
        $('.save').click(function () {
            alert('saveworking');
        });

        $('.add_row').click(function () {
            alert('add_row');
        });
    });
</script>

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

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