肥皂起泡泡
2021-10-21 15:01:30
還不太精通 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 回答

收到一只叮咚
TA貢獻1821條經驗 獲得超5個贊
與您在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>

四季花海
TA貢獻1811條經驗 獲得超5個贊
您的str
變量不等于元素內的文本節點,而是元素本身。要使str
元素內的文本相等,請嘗試以下操作。
var str = document.getElementById("demo").innerText;

江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
您需要在替換之前從元素中提取文本。
//Replace the digits
var res = str.innerHTML.replace(pat, ': 54321');
添加回答
舉報
0/150
提交
取消