还不太精通 JS,我遇到了一个奇怪的问题,它似乎.replace() 应该可以工作,但实际上却没有。我只是想获取一个包含文本 + 数字的字符串(来自元素 ID),用 RegEx 模式替换数字,然后用原始文本 + 新数字替换该 ID 中的原始文本。我的 HTML 示例:<html> <body> <p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p> <p id="demo">Movies: 1234!</p> <button onclick="myFunction()">Try it</button> </body></html>我的JS:function myFunction() { // Get all the text in #id=demo var str = document.getElementById("demo"); // RegEx pattern to find ": <some digits>" var pat = /\:\s?\d*/; // Replace the digits var res = str.replace(pat, ': 54321'); // Doesn't work (as a test) ... //res = " hi" // Replace the text in id=demo with original text + new digits. str.innerHTML = res; // Doesn't work (as a test) ... //document.getElementById("demo").innerHTML = res;}目前,点击页面中的按钮后,什么也没有发生。这也可能有点帮助:https : //codepen.io/stardogg/pen/aboREmL
3 回答
![?](http://img1.sycdn.imooc.com/54586425000103f602200220-100-100.jpg)
收到一只叮咚
TA贡献1821条经验 获得超4个赞
与您在innerHTML函数的最后一行设置相同的方式,innerHTML也是您应该应用的replace内容:
function myFunction() {
var str = document.getElementById("demo");
var pat = /\:\s?\d*/;
var res = str.innerHTML.replace(pat, ': 54321');
str.innerHTML = res;
}
<p>Click the button to replace "Movies: 12344" with "Movies: 54321" in the paragraph below:</p>
<p id="demo">Movies: 1234!</p>
<button onclick="myFunction()">Try it</button>
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
四季花海
TA贡献1811条经验 获得超5个赞
您的str
变量不等于元素内的文本节点,而是元素本身。要使str
元素内的文本相等,请尝试以下操作。
var str = document.getElementById("demo").innerText;
![?](http://img1.sycdn.imooc.com/54584cb50001e5b302200220-100-100.jpg)
江户川乱折腾
TA贡献1851条经验 获得超5个赞
您需要在替换之前从元素中提取文本。
//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');
添加回答
举报
0/150
提交
取消