我有以下html,我想用带有空格的下划线替换所有出现在div xyz
<div class="xyz">
<b><a>Hello_1</a></b>
</div>
<div class="xyz">
<b><a>Hello_2</a></b>
</div>
以下不起作用?
$('.xyz').each(function() {
var $this = $(this);
$this.find('a').text().replace(/_/g, ' '));
});
答案 0 :(得分:5)
正则表达式没有问题。您没有更新DOM中的文本。
.text()
给出了textContent
元素,它没有设置它。您可以使用text()
setter,如下所示
$('.xyz a').text(function(i, text) {
return text.replace(/_/g, ' ');
});
$('.xyz a').text(function(i, text) {
return text.replace(/_/g, ' ');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="xyz">
<b><a>Hello_1</a></b>
</div>
<div class="xyz">
<b><a>Hello_2</a></b>
</div>
答案 1 :(得分:2)
您忘了替换您更改的文字
$('.xyz').each(function() {
$(this).find('a').each(function(){
var newText = $(this).text().replace(/_/g, ' ');
$(this).text(newText);
});
});
在评论后编辑
答案 2 :(得分:0)
需要......
var newText = $this.find('a').text().replace(/_/g, ' '));
$(this).find('a').text(newText);
在循环中遍历DOM usig find是一种昂贵的方法。您可以循环并将所有锚标记首先放入数组中,这可能也取决于锚标记的数量。
答案 3 :(得分:0)
循环后替换dom元素。
{
"name": "example-app",
"version": "1.0.0",
"description": "Example App",
"main": "index.js",
"scripts": {
"start": "nodemon --use_strict index.js",
"bundle": "webpack"
},
"license": "ISC",
"dependencies": {
"bcrypt": "^1.0.2",
"body-parser": "^1.17.2",
"bootstrap": "^4.0.0-alpha.6",
"express": "^4.15.4",
"jsonwebtoken": "^7.4.3",
"material-ui": "^0.19.0",
"mongoose": "^4.11.7",
"passport": "^0.4.0",
"passport-local": "^1.0.0",
"react": "^15.6.1",
"react-addons-css-transition-group": "^15.6.0",
"react-addons-transition-group": "^15.6.0",
"react-dom": "^15.6.1",
"react-router-dom": "^4.2.2",
"react-tap-event-plugin": "^2.0.1",
"reactstrap": "^4.8.0",
"validator": "^8.0.0"
},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"babel-plugin-transform-class-properties": "^6.24.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"clean-webpack-plugin": "^0.1.16",
"css-loader": "^0.28.5",
"file-loader": "^0.11.2",
"html-webpack-plugin": "^2.30.1",
"nodemon": "^1.11.0",
"style-loader": "^0.18.2",
"url-loader": "^0.5.9",
"webpack": "^3.5.5",
"webpack-dev-server": "^2.7.1"
}
}
&#13;
$('.xyz').each(function() {
var $this = $(this).find('a');
$this.text( $this.text().replace(/_/g, ' '));
});
&#13;