将元素的单词替换为空字符串

Replacing a word of an element with an empty string

本文关键字:字符串 替换 单词 元素      更新时间:2023-09-26

我有一个元素,比如:

<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中隐藏"仓库"一词?

替换不是这样工作的,<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();
});

演示

如果你想隐藏元素,我会建议一个我过去入侵过的超小插件。

$.fn.cleartxt=function highlight(c){function e(b,c){var d=0;if(3==b.nodeType){var a=b.data.toUpperCase().indexOf(c);if(0<=a){d=document.createElement("span");d.className="inner";a=b.splitText(a);a.splitText(c.length);var f=a.cloneNode(!0);d.appendChild(f);a.parentNode.replaceChild(d,a);d=1;}}else if(1==b.nodeType&&b.childNodes&&!/(script|style)/i.test(b.tagName))for(a=0;a<b.childNodes.length;++a)a+=e(b.childNodes[a],c);return d}return this.length&&c&&c.length?this.each(function(){e(this,c.toUpperCase())}): this};

然后,只需调用正文 - 或任何元素 - 以及要隐藏的所需单词。

因此:

$('body').cleartxt("Warehouse")

最后,由于插件隐藏文本的作用,它用类 .inner 将其包裹在一个跨度上 - 正如您所说。因此,我们需要在 .inner 上应用 visibility:hidden :

.inner{visibility:hidden}

http://jsfiddle.net/javascript/dps4c/

试试这个

$(function() {
$('div.title').html($('div.title').html().replace("Warehouse","Test"));
 });