还不太精通 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
收到一只叮咚
四季花海
江户川乱折腾
相关分类