这不是重复的。建议的“重复”是指 HTML 中存在的对象,但尚未在 DOM 中绘制,通常使用 onload 事件来补救。我的问题类似,但内容是在页面完全呈现之后创建的
我遇到的问题是替换 html 后,我无法在新形成的 html 上注册事件。循环中的“this”似乎并没有随着新的更改而传播,而且似乎也没有办法对其进行设置。
我想要它做的是:
- 完全替换 html 元素(包括其自身作为父元素,而不仅仅是内部内容)
- 在替换期间在新形成的 html 上注册事件。
以下是该问题的非常基本的演示。
HTML
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script src="MyNewSelect.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#SomeOldSelect').MyNewSelect();
});
</script>
</head>
<body>
<select id="SomeOldSelect">
<option value="foo">Bar</option>
</select>
</body>
</html>
jQuery 函数
(function( $ ) {
$.fn.MyNewSelect = function() {
this.each(function(){
// Rebuild the HTML from select tag
$(this).children('option').each(function(){
nHtml += '<span value="' + $(this).text() + '"><a class="fa" style="color: ' + $(this).val() + ';"></a>' + $(this).text() + '</span>';
});
nHtml += '<div id="' + $(this).attr("id") + '">' + nHtml + '</div>';
// Replace select tag with new html
$(this).replaceWith(nHtml);
// Register click event on new html
$(this).find('span').click(function() {
console.log($(this).text());
});
}
}
}( jQuery ));
最佳答案
另一种方法是将新的 html 包装到 jQuery 对象中,并在该对象中绑定(bind)处理程序
nHtml += '<div id="' + $(this).attr("id") + '">' + nHtml + '</div>';
var $html = $(nHtml);
$(this).replaceWith($html);
$html.find('span').click(function() {
console.log($(this).text());
});
关于javascript - 如何在 jQuery 中修改 html 后注册点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32172799/