0

我有,例如:

$first = $('#firstElement').click(function() { });

但是在页面执行的某个时刻,我将用另一个元素替换该元素:

$newElement = jQuery('<div />');
$first.replaceWith($newElement);

但我想将第一个元素的回调保留在第二个元素中......

那可能吗?

编辑 1

我已经知道如何使用.on()or来做到这一点.delegate()。这是我的场景:

一旦选择器更改,我需要加载一些内容,但是,该选择器的内容将根据登录用户的角色而有所不同。我已经将信息存储在localstorage. 该选择器的内容通过以下方式加载:

window.Core.setBranchesSelector($('#theElementInWhichTheSelectorWillBe'));

该函数创建一个<select>元素。我可以在js该页面内进行:

$('#parent').on('click', '#theElementInWhichTheSelectorWillBe', function() {});

但我想让该功能尽可能灵活,因此,如果我做出如下想法:

$elementToBeReplaced = $('<coolElement />').click(function() {});
/* Something really cool with that element */
Core.setBranchesSelector($elementToBeReplaced);

选择器继承click事件的回调...

4

3 回答 3

2

对您的问题的简单回答:不,您不能这样做。至少在新版本的 jQuery 中没有(使用 1.7 你可以这样做,因为@undefined 已经在答案#15708467 的评论中声明)。

但是,这是一个使用.on()委托的简单示例:

http://jsfiddle.net/8dCQT/

$(function() {
    $("#parent").on("click", ".child", function() {
        alert($(this).text());
    });
    $("input").click(function() {
        $(".child").remove();
        $("#parent").append("<div class='child'>I'm a replacement</div>");
    });
});

单击按钮后,您会注意到,单击替换 div 会调用相同的单击函数并使用新 div 的文本发出警报。

Note: the important part here is that the replacement be selectable with the same selector (in this case .child) as the original. I used a class here, but I could have used first child of the parent, or whatever else works.

Also note: You don't have to bind to an immediate parent either, you can bind all the way at the top with document, but that's not recommended because it will slow down your code. You should bind as close to the elements you want to attach events to as possible so the code won't have to walk too far down the DOM tree.

于 2013-03-29T17:44:26.087 回答
1

jQuery 不提供直接访问已绑定事件的 API。

将事件放在父元素上,替换子元素,并依靠事件冒泡来捕获它。

于 2013-03-29T17:39:06.550 回答
1

您要么需要在每个元素中包含相同的 id,要么为每个 div 提供一个公共类。一旦你这样做了,它就像:

$(document).on('click','.some-common-class',function(){
});
于 2013-03-29T17:39:37.067 回答