0

我写下一段代码:

<span id="post">search by id</span>


$("#post").click(function () {
    var input = $("<input type='text' id='input_find_by_id'><button type='button' id='button_search_by_id'>Click Me!</button>");
    $(this).replaceWith(input);
    setTimeout(function() {change();},1250);
});


function change() {
    var input = $("<span id='post'><u>search by id</u></span>");
    $("#input_find_by_id").replaceWith(input);
    $("#button_search_by_id").remove();
    //input.select();
}

http://jsfiddle.net/alonshmiel/APjyy/2/

当我按下“按ID搜索”时,它变成了一个按钮,然后,1分钟后,它返回“按ID搜索”。

但是当我再次尝试按下它时,什么也没有发生。为什么我不能再次获得按钮?

4

6 回答 6

1

您不再有新创建的元素上的事件处理程序。

将您的事件处理程序更改为在文档上并在匹配特定选择器时进行处理。这样,您的事件处理程序将为满足选择器条件的每个新元素触发:

$(document).on('click', '#post', function () {
    var input = $("<input type='text' id='input_find_by_id'><button type='button' id='button_search_by_id'>Click Me!</button>");
    $(this).replaceWith(input);
    setTimeout(function() {change();},1250);
});
于 2013-06-10T10:17:01.953 回答
1

当您将原始 span 替换为其他内容时,您实际上从 DOM 中删除了该元素 - 以及附加到它的任何事件。当您再次添加您的跨度(在change函数中)时,它是一个新创建的元素,它没有附加任何事件处理程序 - 您需要再次附加事件处理程序。

解决这个问题的替代方法是使用jQueryon函数来附加“实时”事件处理程序:

$(document).on('click', '#post', function () {
    ...
});

此外,由于您只调用一个没有参数的函数setTimeout,您可以将其简化为

setTimeout(change, 1250);
于 2013-06-10T10:17:35.147 回答
1

您可以通过隐藏文本并取消隐藏已经存在但隐藏的按钮来做到这一点

于 2013-06-10T10:21:46.470 回答
1

使用这个:您在 change() 函数下添加“post” id 元素:

$("#post").click(function () {
        var input = $("<input type='text' id='input_find_by_id'><button type='button' id='button_search_by_id'>Click Me!</button>");
        $(this).replaceWith(input);
        //setTimeout(function() {change();},1250);
    });


    function change() {
        var input = $("<u>search by id</u>");
        $("#input_find_by_id").replaceWith(input);
        $("#button_search_by_id").remove();
        //input.select();
    }
于 2013-06-10T10:21:59.950 回答
1

我已经更新了小提琴。http://jsfiddle.net/APjyy/6/

当您search by id第一次单击“”时,您必须将rebind其设置为"#post"。因为,您正在从中删除元素DOM,因此事件侦听器也将被删除。当您重新添加元素时,jQuery对它一无所知,因此侦听器不起作用。

您需要使用事件delegation

$("body").on('click', '#post' , function () {

});

请参阅此处的文档。http://api.jquery.com/on/

于 2013-06-10T10:22:28.377 回答
1

将搜索框替换为“post”跨度后,您不会将点击事件重新绑定到该跨度。

这里的例子,即使我觉得不是很漂亮:http: //jsfiddle.net/APjyy/5/

function change() {
    var input = $("<span id='post'><u>search by id</u></span>");

    $("#input_find_by_id").replaceWith(input);
    $("#button_search_by_id").remove();
    //input.select();

    $("#post").click(function () {
        var input = $("<input type='text' id='input_find_by_id'><button type='button' id='button_search_by_id'>Click Me!</button>");
        $(this).replaceWith(input);
        setTimeout(function () {
            change();
        }, 1250);
    });
}
于 2013-06-10T10:19:37.743 回答