我试图替换文本每次我有一个输入的变化。
下面是一个例子:https://jsfiddle.net/ewdp3Lnr/
$("[name='replacer']").on('change paste keyup', function() {
PRO_Content = $('#content').html();
PRO_Content = PRO_Content.replace('####', $("[name='replacer']").val());
$('#content').html(PRO_Content);
});
它正在工作,但只对第一个检测到的更改。
但不为第二,第三,…
你能给我指个正确的方向吗?谢谢。
在任何更改之前获取内容并使用初始值。不要重写初始值,因为那会取代####
var pattern = $('#content').html();
$("[name='replacer']").on('change paste keyup', function() {
PRO_Content = pattern.replace('####', $("[name='replacer']").val());
$('#content').html(PRO_Content);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Put something here to replace the #### in the HTML code:<br>
<input type="text" name="replacer">
<hr>
<span id="content">
<p>This man is <strong style="color:red">####</strong>.</p>
</span>
可以使用。text(function)来简化代码。
此外,您可以使用input事件代替change和keyup事件。
代码片段:
var element = $('#content :contains("####")').filter((i,e) => e.textContent == '####');
$("[name='replacer']").on('input paste', function(e) {
element.text(function(idx, text) {
return e.target.value;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="replacer">
<hr>
<span id="content">
<p>This man is <strong style="color:red">####</strong>.</p>
</span>