jQuery不会根据需要删除所有内容 [英] Jquery does not remove all content as desired
问题描述
我的网页上有以下代码.
I have the following code on my web page.
<div id="phoneDiv">+7 (999) 999-9999
<div class="editmode">
<input type="text" placeholder="Телефон" value="+7 (999) 999-9999" id="editPhone" name="editPhone" class="text key">
</div>
</div>
我只需要删除文本而不删除div.editmode
.
I need to remove just the text without removing of div.editmode
.
我使用了该功能:
$(document).on('click','#phoneDiv',function(){
$("#phoneDiv").not('div.editmode, div.editmode *').remove();
});
但是它只是删除了所有内容.
but it just removes all the content.
为什么这不起作用?这是我的 jsfiddle
Why is this not working? Here is my jsfiddle
推荐答案
首先,这不是您应该使用.not()
的方式.它用于过滤正在处理的实际JQuery对象中的元素(在您的情况下,您选择#phoneDiv
),而不是其子元素...
First of all, that's not how you should use .not()
. It is used to filter the elements in the actual JQuery object you're dealing with (in your case, you're selecting #phoneDiv
), not its children...
但是,要删除文本,您需要以其他方式定位文本,因为它实际上并不是元素.您可以通过.contents()
获取它.对其进行过滤以排除div元素,然后执行.remove()
But, to remove the text, you'd need to target it in a different way, since it is not actualy an element. You can get it through .contents()
. Filter it to exclude the div element, and then perform the .remove()
$(document).on('click','#phoneDiv',function(){
$("#phoneDiv").contents().filter(function() {
return (!$(this).is(".editmode"));
}).remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="phoneDiv">+7 (999) 999-9999
<div class="editmode">
<input type="text" placeholder="Телефон" value="+7 (999) 999-9999" id="editPhone" name="editPhone" class="text key" />
</div>
</div>
这篇关于jQuery不会根据需要删除所有内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!