好吧,假设我在下面的 anchor 元素上添加了 Handlebars 。 我想在点击后触发一个事件。但是,在我插入它之后,javascript 事件对其不起作用。这就是我的意思:
<div class="list-group" id="listGroup">
<a class="list-group-item" href="#" name="jumanji">JUMANJI</a>
<a class="list-group-item active" href="#" name="looper">LOOPER</a>
<a class="list-group-item" href="#" name="lone_survivor">LONE SURVIVOR</a>
<a class="list-group-item" href="#" name="the_dark_knight">THE DARK KNIGHT</a>
<a class="list-group-item" href="#" name="world_war_z">WORLD WAR Z</a>
<script id="list" type="text/x-handlebars-template">
{{#fill this}}
<a class="list-group-item" id="joe" href="#">{{name}}</a>
{{/fill}}
</script>
</div>
插入最后一个带 Handlebars 的 anchor 元素后,我想通过单击它来触发事件,例如:
$('#joe').click(function () { alert ("hi"); }
但这就像乔不存在一样,但是,我可以通过单击其他内容并从那里引用它来到达乔。假设还有另一个 id 为“moe”的元素,那么我就可以这样做。
$('#moe').click(function () { alert($('#joe').html()); }
希望我说清楚了,谢谢。
最佳答案
尝试使用 on()进行事件委托(delegate)功能:
$(document).on('click','#joe',function () { alert ("hi"); }
关于javascript - 通过单击 Handlebars 插入的 anchor 元素来触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25701003/