Jquery 如果元素具有类替换元素';文本';与';一些文本';
我有一个标签元素:Jquery 如果元素具有类替换元素';文本';与';一些文本';,jquery,Jquery,我有一个标签元素: <form id="new_user"> <div id="first-name"> <label for="user_profile_attributes_first_name"><abbr title="required">*</abbr> First name</label> </div> </form> 谢谢 我建议: if $('#new_user').hasClass
<form id="new_user">
<div id="first-name">
<label for="user_profile_attributes_first_name"><abbr title="required">*</abbr> First name</label>
</div>
</form>
谢谢 我建议:
if $('#new_user').hasClass('team-registration') {
var text = $(this).text();
$(this).text(text.replace('First','Team')
}
在上面的例子中,我只选择替换字符串'First',因为第二个单词('name')在两者之间是一致的
当然,我要指出,您提供的标记中没有id=“new_user”
元素,因此我强烈建议您确保使用正确的id
选择器,因为这种方法将替换匹配元素中的文本,它不会尝试在匹配元素的子元素中搜索要替换的字符串
参考资料:
html
而不是text
,因为#new_user
似乎包含其他元素text
将删除这些标记并为您提供平面文本,而html
作用于实际的innerHTML
注意:string.replace(string,string)
只替换第一次出现的字符串。如果需要替换所有引用,请使用正则表达式:
return html.replace(/First name/g, "Team name");
请注意,在将要发布的文本之前,我有*replaced@RooticalV. 是否要简单地将
#new_user.team registration
的所有内容替换为“team name”
?还是希望它产生“*团队名称”
?此外,问题中的HTML代码片段与所需条件不匹配。如果你更新了你的问题以包含正确的HTML以及预期的结果HTML,这会有所帮助。我已经编辑了HTML。是的,我只希望文本被替换,并*保留在原处。谢谢@RooticalV。那么这就可以满足你的要求了html.replace
将查找所有出现的“First name”
,并将其替换为“Team name”
,以保持所有其他html的完整性。
$("#new_user.team-registration").html(function(i, html) {
return html.replace("First name", "Team name");
});
return html.replace(/First name/g, "Team name");