将元素的单词替换为空字符串
Replacing a word of an element with an empty string
我有一个元素,比如:
<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"));
});
相关文章:
- 字符串替换-不支持格式字符'}'
- Unicode字符串替换不适用于完整的变音符号阿拉伯文本
- Javascript 将字符串替换为
返回为空 - 字符串替换只替换第一个匹配项,可以'不要让它全球化
- javascript字符串替换$1(如果它是某个值)
- 字符串替换正则表达式,开头为空格
- 将 url 中的一个字符串替换为另一个字符串
- 在HTML文本框中查找某些子字符串,然后用其他字符串替换它们
- 我想使用replace函数扫描json对象,然后用字符串替换匹配的单词
- 字符串替换为从右向左的语言(阿拉伯语)
- 将字符串替换为用户键入的文本
- 字符串替换javascript
- JavaScript 将多行字符串替换为多行字符串
- Javascript字符串替换不起作用
- 字符串替换不'当通过android webView JavascriptInterface传递字符串时无法工作
- 我正在尝试用另一个字符串替换一个字符串
- 字符串替换最后一个字符出现的斜杠
- 将具有的字符串替换为$
- 基于查询字符串替换HTML
- Javascript字符串替换在满足长度而不是instantanoeus之前不会生效