jQuery切换不适用于通过execCommand insertHTML插入div中的元素
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="application/javascript">
$(function() {
$("#paste").click(function() {
document.execCommand("insertHTML", false, "<div class='foobar'><p class='foo'>Spoiler</p><p class='bar'>" + window.getSelection().getRangeAt() + "</p></div>");
});
$(".foo").each(function() {
$(this).click(function() {
$(this).next().toggle();
})
});
});
</script>
<style>
.content {
widt:300px;
height:200px;
border:1px solid #000;
margin-bottom:10px;
}
.foo {
border:1px solid #000;
cursor:pointer;
}
.bar {
border:1px solid #000;
}
</style>
</head>
<body>
<button id="paste">Spoiler</button>
<div contenteditable="true" class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra sapien diam, id ornare eros pulvinar quis. Nam volutpat consequat tellus nec gravida. Proin vestibulum nisl a adipiscing semper. Sed bibendum tortor ligula, ac ultricies nulla bibendum vitae. Morbi a leo tortor. Vestibulum tincidunt placerat erat, eu vulputate nisi elementum quis. Quisque ac odio in massa hendrerit aliquam ut a diam. Pellentesque nunc nibh, fringilla nec lectus vel, dictum tincidunt arcu.</div>
</body>
</html>
答案 0 :(得分:0)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="application/javascript">
$(function() {
$("#paste").click(function() {
document.execCommand("insertHTML", false, "<div class='foobar'><p class='foo'>Spoiler</p><p class='bar'>" + window.getSelection().getRangeAt() + "</p></div>");
$(".foo").unbind();
$(".foo").each(function() {
$(this).click(function() {
$(this).next().toggle();
})
});
});
});
</script>
<style>
.content {
widt:300px;
height:200px;
border:1px solid #000;
margin-bottom:10px;
}
.foo {
border:1px solid #000;
cursor:pointer;
}
.bar {
border:1px solid #000;
}
</style>
</head>
<body>
<button id="paste">Spoiler</button>
<div contenteditable="true" class="content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse pharetra sapien diam, id ornare eros pulvinar quis. Nam volutpat consequat tellus nec gravida. Proin vestibulum nisl a adipiscing semper. Sed bibendum tortor ligula, ac ultricies nulla bibendum vitae. Morbi a leo tortor. Vestibulum tincidunt placerat erat, eu vulputate nisi elementum quis. Quisque ac odio in massa hendrerit aliquam ut a diam. Pellentesque nunc nibh, fringilla nec lectus vel, dictum tincidunt arcu.</div>
</body>
</html>
我找到了解决方案,事件监听器监听最初在dom中的元素,但不监听稍后插入的元素。因此,解决方案是取消绑定侦听器并再次绑定http://jsfiddle.net/YDvSe/4/