我有一个像这样的元素:
<div class="title">Headquarters<br />
Warehouse</div>
我无法使用 CSS 隐藏 .title
中的单词,因此我尝试使用 jQuery:
$(function() {
$('div.title')
.html($('div.title').html().replace("Headquarters" + "<br />" + "Warehouse", "Test"));
});
但这并没有改变任何东西:http://jsfiddle.net/NAm66/
如何在 .title
中隐藏“warehouse”一词?
最佳答案
替换不起作用 <br />
是一个 html 元素而不是字符串。
用你正在做的事情做:
$('div.title').empty();
或者如果您想用其他内容替换内容,则:
$('div.title').html("Test"); //or .text("Test")
或者只是这样做:
$(function () {
$('div.title').contents().each(function () {
if(this.nodeType ===3 && this.nodeValue === "Warehouse"){
this.nodeValue = '';
return false;
}
});
});
或者
$(function () {
$('div.title').contents().filter(function () {
return this.nodeType === 3 && this.nodeValue === "Warehouse";
}).remove();
});
<强> Demo
关于javascript - 用空字符串替换元素的单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20009216/