javascript 使用 jQuery 从 div 中删除特定内容?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7302990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove Specific Content from div with jQuery?
提问by Shahmeer Navid
Can you remove specific content from an element with jQuery?
您可以使用 jQuery 从元素中删除特定内容吗?
So for example, if I had
例如,如果我有
<p>Hello, this is a test</p>
could I turn it into
我可以把它变成
<p>this is a test</p>
with jQuery (or any Javascript)
使用 jQuery(或任何 Javascript)
Please keep in mind that I just want to remove the "Hello, " so
请记住,我只想删除“你好”,所以
$(p).innerHTML("this is a test");
wont work
行不通
回答by Simon Arnold
var str = $('p').text()
str.replace('Hello,','');
$('p').text(str);
For more information visit: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
更多信息请访问:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/replace
回答by ?ime Vidas
Do it like so:
这样做:
$( elem ).text(function ( i, txt ) {
return txt.replace( 'Hello,', '' );
});
where elem
is the reference to the DOM element which text content you want to modify.
哪里elem
是对要修改的文本内容的 DOM 元素的引用。
回答by AlexBay
You don't need jQuery for this.
为此,您不需要 jQuery。
First get your element's HTML (if you have only one of them, use jQuery.each otherwise):
首先获取您元素的 HTML(如果您只有其中一个,则使用 jQuery.each 否则):
var p = document.getElementsByTagName('p')[0];
var str = p.innerHTML;
Then, if you want to remove exactly "Hello, " do this:
然后,如果您想完全删除“Hello”,请执行以下操作:
str = str.substring(7);
If you want everything after the coma use:
如果你想在昏迷后使用一切:
str = str.split(',', 2)[1];
And set its HTML back with:
并将其 HTML 设置回:
p.innerHTML = str;