按照我标记 HTML 的方式......
<textarea></textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
是否可以更改 .body
内的 html无需更改 .content
内的 html ?
编辑:
我正在使用我的代码编辑器和我的 <script>
在这种情况下,标签被替换为 .content
,和<body>
标签替换为 .body
.
.before
API 似乎是适合我的情况的最佳解决方案,除非仅添加 3 个字符(例如,哈哈)。结果为.body
是(例如 lolollol)
$('textarea').keyup(function() {
$('.content').before(this.value)
return false
}).trigger('keyup')
textarea {
width: 98%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea></textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
最佳答案
这很棘手,因为 .body
可能包含文本节点。
jQuery 的 contents()
方法有帮助:
$('textarea').keyup(function() {
$('.body')
.contents() //get both text nodes and element nodes
.each(function() {
if(this.className !== 'content') {
this.nodeValue= this.innerHTML= ''; //nodeValue needed for text nodes,
//innerHTML for element nodes
}
});
$('.content').before(this.value);
}).trigger('keyup');
textarea {
width: 98%;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<ol>
<li>test data here</li>
</ol>
</textarea>
<div class="body">
<div class="content">don't change this</div>
</div>
关于javascript - 更改 HTML 元素但忽略最后一个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36703564/