用jQuery显示内联确认

时间:2012-09-09 08:45:51

标签: javascript jquery html web

我正在尝试为链接创建“您确定”确认,类似于reddit帖子上的报告按钮上的确认。单击时,链接将替换为“您确定是/否”,其中“是”将执行操作,“否”将恢复链接。我可以用确认替换链接,但无法获得“否”链接以隐藏确认。

相关代码:

<span id="confirm"><a href="#>Confirm</a></span>


<script type="text/javascript">
$(function() {

   $("#confirm").click(function() {
     $(this).html('Are you sure? <a href="#">Yes</a> / <a id="unconfirm" href="#">No</a>');
   });

   $("#unconfirm").click(function() {
     $(this).parents("span").html('<a href="#">Confirm</a>');
   });

 });
</script>

2 个答案:

答案 0 :(得分:5)

执行事件绑定时,DOM中不存在#unconfirm元素。您需要在DOM树中进一步委托事件处理程序:

$(document).on("click", "#unconfirm", function() {
    $(this).parents("span").html('<a href="#">Confirm</a>');
});

这使用.on()方法,它将事件处理程序绑定到所选元素(document),但只有在事件源于与第二个参数匹配的元素时才执行处理函数({ {1}})。

请注意,jQuery 1.7中添加了#unconfirm。如果您使用旧版本,则可以使用.on()代替。

另请注意,将.delegate()替换为其他祖先元素会更有效(从那时起,事件的行程距离会减少,直到触发委托事件处理程序为止。)

答案 1 :(得分:1)

由于您的#unconfirm元素是动态生成的,因此您需要使用on()委托来附加事件:

$(closestStaticParent).on('click', '#unconfirm', function() { ... })