最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - I want to refresh dom if new element (clone object) appended in inner html - Stack Overflow

programmeradmin3浏览0评论

I want to auto bind events of element(s) if i append element into DOM and the element is clone object. Here is code snippet:

HTML:

<input type="button" class="clickme" value="Click Me" />​

Javascript:

$(document).ready(function(){
    $(".clickme").click(function(){
        alert("Clicked");
        var cloneElem = $(this).clone();
        //cloneElem.bind("click");
        cloneElem.attr("value", "Click Me" + $("input").length.toString());
        $(this).parent().append(cloneElem);
    });
});​

Result:

If I click on Click Me1 then it should also trigger a event which is similar to Click Me

Note: I don't want to use Live function of JQuery to trigger event.

I want to auto bind events of element(s) if i append element into DOM and the element is clone object. Here is code snippet:

HTML:

<input type="button" class="clickme" value="Click Me" />​

Javascript:

$(document).ready(function(){
    $(".clickme").click(function(){
        alert("Clicked");
        var cloneElem = $(this).clone();
        //cloneElem.bind("click");
        cloneElem.attr("value", "Click Me" + $("input").length.toString());
        $(this).parent().append(cloneElem);
    });
});​

Result:

If I click on Click Me1 then it should also trigger a event which is similar to Click Me

Note: I don't want to use Live function of JQuery to trigger event.

Share Improve this question asked May 24, 2012 at 8:03 XulfeeXulfee 9863 gold badges13 silver badges44 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 9

.clone takes an argument whether or not to clone events as well:

$(this).clone(true);
$(document).ready(function(){
    function do_logic() {
        alert("Clicked");
        var cloneElem = $(this).clone();
        cloneElem.click(do_logic);
        cloneElem.attr("value", "Click Me" + $("input").length.toString());
        $(this).parent().append(cloneElem);
    }

    $(".clickme").click(do_logic);
});​

If you don't want every handler to be cloned, this example should work.

$(document).ready(function(){
    $(".clickme").click(function(){
        alert("Clicked");
        var cloneElem = $(this).clone();
        cloneElem.click(function(){
           // code to be executed when you click cloned element.
        })

        //cloneElem.bind("click");
        cloneElem.attr("value", "Click Me" + $("input").length.toString());
        $(this).parent().append(cloneElem);
    });
});​

you have to add click event to cloned element also.

one way to do this ..

$(".clickme").click(AddClone());

function AddClone() {
    alert("Clicked");
    var cloneElem = $(this).clone().click(AddClone());
    //cloneElem.bind("click");
    cloneElem.attr("value", "Click Me" + $("input").length.toString());
    $(this).parent().append(cloneElem);
}
发布评论

评论列表(0)

  1. 暂无评论