Javascript jQuery:克隆元素和事件

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

jQuery: clone elements AND events

javascriptjqueryeventsappendclone

提问by Omar

Whenever I use ajax to dynamically create new content, .clone(), append() etc, the new element looses any triggers and events I programmed =(

每当我使用 ajax 动态创建新内容、.clone()、append() 等时,新元素都会丢失我编写的所有触发器和事件 =(

After making copy, simple things that WORK on other elements like adding a class to , on the copied elements no longer work. Any new ajax content does not work. Command buttons no longer work. What can I do?

复制后,在其他元素上工作的简单事情,例如在复制的元素上添加类,不再工作。任何新的 ajax 内容都不起作用。命令按钮不再起作用。我能做什么?

I am cloning this HTML, and the command buttons no longer work. Styling the span elements no longer work on the CLONED elements:

我正在克隆这个 HTML,命令按钮不再起作用。样式 span 元素不再适用于 CLONED 元素:

<div name="shows" id="x"><br/> <!-- The ID depends on the database-->
    <div name="shows" id="x">
        ID: <input disabled="disabled" size="7" value="x" name="id" />
        Status: 
        <select name="status" >
          <option selected="selected" >Display</option>
          <option >Hide</option>
        </select>
        <br/><br/>
        <span class="required" id="date_txt">*Date: </span><input type="text" value="" name="date" />
        &nbsp;&nbsp;
        <span class="required" id="title_txt">*Title: </span><input type="text" size="65" value="" name="title" />
        <br/>
        <span class="required" id="venue_txt">*Venue: </span><input type="text" size="45" value="" name="venue" />
        Telephone: <input type="text" value="" name="tel" />
        <br/>
        URL: <input type="text" size="100" value="" name="url" />
        <br/><br/>
        Address: <input type="text" size="45" value="" name="address" />
        &nbsp;&nbsp;
        <span class="required" id="city_txt">*City: </span><input type="text" value="" name="city" />
        <br/>
        State: <input type="text" value="" name="state" />
        ZIP: <input type="text" value="" name="zip" />
        <span id="country_txt">*Country: </span><input type="text" value="United States" name="country" />
        <br/>
        <br/>Comments: <br/>
        <textarea cols="80" rows="8" name="comments" ></textarea>
    </div>
    <!-- START OF:commands  -->
    <div id="commands" >
        <button name="edit" id="edit" >Edit</button> 
        <button name="delete" id="delete" >Delete</button>
    <br />
    <hr />
    <br />
    </div>
    <!-- END OF:commands  -->
</div>
<!-- END OF:new -->

New comments added, 11/03/2011:

添加了新评论,11/03/2011:

OK, I figured out the problem and I had an error on my jQuery. Now, when I add .clone( true ) ALMOST everything works.

好的,我找到了问题所在,我的 jQuery 出错了。现在,当我添加 .clone( true ) 时,几乎一切正常。


My new problem is the UI datepicker. After cloning the HTML, when I click on the newly cloned date field, the focus goes to the (old) datefield the data was cloned from. More over, if I select a date, the value goes to the old datefield -Not the newly cloned datefield.


我的新问题是 UI 日期选择器。克隆 HTML 后,当我单击新克隆的日期字段时,焦点将转到从中克隆数据的(旧)日期字段。更重要的是,如果我选择一个日期,该值将转到旧的日期字段 - 而不是新克隆的日期字段。

Here is my ajax code (After a successful submition):

这是我的ajax代码(成功提交后):

UI datepicker code:

UI日期选择器代码:

$("input[name='date']").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, numberOfMonths: 3, showButtonPanel: true});

Ajax:

阿贾克斯:

    ...ajax code...
function(data)
{
var $msg = eval(data);
if( $msg[0] == 1 )
    {
    //#var.new
        $id = '#'+$msg[1];
        $data = $("#new");
    $new = $data.clone(true);
    $new.find('input.datefield').datepicker();


        $new.attr("id", $id);
        $new.children('[name="id"]').val($id);
        $new.children('[name="id"]').attr("value", $id);
        $new.children(":input").each(function() { var $value = $(this).val(); $(this).attr("value", $value); });
        $new.prepend( "<br/>" );

        $commands = $("#blank").children("#commands").clone(true);
        $commands.children("#add").text("Update");
        $commands.children("#add").attr("pk", $id);
        $commands.children("#add").attr("name", "update");
        $commands.children("#add").attr("id", "update");

        $commands.children("#reset").text("Delete");
        $commands.children("#reset").attr("pk", $id);
        $commands.children("#reset").attr("name", "delete");
        $commands.children("#reset").attr("id", "delete");

        $new.append( $commands );

        //#animation
        //blank.slideUp
        $("#blank").slideUp(2500, function(){
        $("#ADDNEW").html("&#9658; New:");
        //$("#blank").clone().prependTo( $("#active") );
        //$("#blank").prependTo( "#active" );

        //active.slideUp
        $("#active").slideUp("slow", function(){
        $("#ON").html("&#9658; Active:");
        $("#active").prepend( $new );
        $('#reset').trigger('click');

        //active.slideDown
        $("#active").slideDown(8500, function(){
        $("#ON").html("&#9660; Active:");

        //blank.slideDown
        $("#blank").slideDown(3500, function(){
        $("#ADDNEW").html("&#9660; New:");
        load_bar(0);

        }); //end: anumation.#blank.slideDown
        }); //end: anumation.#active.slideDown
        }); //end: anumation.#blank.slideUp
        }); //end: anumation.#active.slideUp

        //$("#new").fadeOut(2000, function(){
        //START: blank
        //alert( $("#blank").html() );
        //$dad = $("#new");
        //$dad.children('input[name!="id"][name!="country"], textarea').val('');
        //$dad.children('[name="country"]').val("United States");
        //$dad.children('[name="date"]').focus();
        //END: blank
        //$("#new").fadeIn(2000, function(){
        //alert( $msg );
        //}); //end: anumation.fadeIn
        //}); //end: anumation.fadeOut
        } //end: if
    else
        {
        //var varMSG = data;
        //alert( "Hello" );
        alert( $msg );

        //$("#add").attr("disabled", false);
        //$("#reset").attr("disabled", false);
        load_bar(0);
        } //end: if.else
    }//end: $.post.function
); //END:$.post
}); 
//END:ajax

回答by ?ime Vidas

.clone( true )does the trick.

.clone( true )诀窍。

Documentation: http://api.jquery.com/clone/

文档:http: //api.jquery.com/clone/

回答by krachleur

Hi I'm having a bit similar use case, I have some dynamically generated content that contains a button, click event is responding to the original button but not the generated one, I've done before :

嗨,我有一个类似的用例,我有一些动态生成的内容,其中包含一个按钮,单击事件响应原始按钮而不是生成的按钮,我以前做过:

$('.someclass').on('click', function() {

but i resolved my problem by replacing the on by live like this :

但我通过像这样用 live 替换 on 解决了我的问题:

$('.someclass').live('click', function() {

回答by Cory Kendall

If your handlers are setup using something like $('.class').click( ... )

如果您的处理程序使用类似 $('.class').click( ... )

Try something like this instead: $('.class').live('click', ...)

试试这样的: $('.class').live('click', ...)

Live applies to elements with the class that may not exist yet.

Live 适用于具有可能尚不存在的类的元素。

回答by Omar

I finally got the UI datepicker to work properly. I had to completely remove datepicker BEFORE cloning and add it AFTER cloning elements. The guys at UI should make it easier for us. Go figure!

我终于让 UI 日期选择器正常工作。我必须在克隆之前完全删除 datepicker 并在克隆元素之后添加它。UI 的人应该让我们更容易。去搞清楚!

Just before cloning:

克隆前:

//#datepicker
$("input[name='date']").datepicker( "destroy" );
$("input[name='date']").removeClass("hasDatepicker").removeAttr('id');

After cloning:

克隆后:

$("input[name='date']").datepicker({ dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true, numberOfMonths: 3, showButtonPanel: true});