我的 html 代码中有一个 ajaxi 页面,第二页中有许多 Div。并编写了一个函数来分割 srting 的第一个字符。问题是每次我重新加载第二页时,它都会一遍又一遍地分割字符串的第一个字符。我只想工作一次。 这是我的切片代码:
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<body>
<div class="removi">,$12547000</div>
<div class="removi">,$24580000</div>
<div class="removi">,$78504000</div>
<script>
$('.removi').text(function (_,txt) {
return txt.slice(1);
});
</script>
</body>
</head>
</html>
最佳答案
只需添加一个简单的 bool 标志,然后检查代码是否已执行:
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>
<body>
<div class="removi">,$12547000</div>
<div class="removi">,$24580000</div>
<div class="removi">,$78504000</div>
<script>
if (window._removedAlready !== true) {
$('.removi').text(function (_,txt) {
return txt.slice(1);
});
window._removedAlready = true;
}
</script>
</body>
</head>
</html>
请记住,污染 window
命名空间不是一个好主意。使用主页中的任何 bool 变量,但不在您的 ajax 内容中。
关于javascript - 在 JQuery 中删除字符串的第一个字符在 dom 中重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39684641/