javascript: 如何使用隐藏标签在不添加换行符的情况下直接更新较大对象的文本?
javascript: how to use a hidden tag to direct text update of larger object without line breaks added?
当然,我们可以像这样更新一个对象的所有文本:
document.getElementById(objId).innerHTML = "some text we like";
我要做的是更新现有文本的子集,要替换的目标由隐藏标签标识。因此,例如,不必在我自己的代码中解析这样的东西:
<p> Here's a huge block of text, many lines long and
**here's the part I want to update,** buried within it and yet there's even more afterwards.</p>
...相反,我想(并且可以)做这样的事情:
<p> Here's a huge block of text, many lines long and <option id="target">**here's the part I want to update,**</option> buried within it and yet there's even more afterwards.</p>
...然后更新为:
document.getElementById("target").innerHTML = "replacement text we like";
不出所料,这行得通,但是,它具有添加换行符的效果,就好像在 <option>
和 </option>
.[=19= 的地方有一个 <br>
标签一样]
这是该调用的有效结果:
<p> Here's a huge block of text, many lines long and<br> replacement text we like<br> buried within it and yet there's even more afterwards.</p>
如何在不插入换行符的情况下执行此操作?
您可以使用 <span>
标签而不是 <div>
来做到这一点。这是一个有效的 JSFiddle.
像<option>
或<div>
这样的元素是块元素。您需要使用内联元素,以便可以使用 <span>
而不是 <option>
:
function myFoo() {
document.getElementById("target").innerHTML = "replacement text we like";
}
<p> Here's a huge block of text, many lines long and <span id="target">**here's the part I want to update,**</span> buried within it and yet there's even more afterwards.</p>
<button id="btn" onclick="myFoo()">Change Text!</button>
当然,我们可以像这样更新一个对象的所有文本:
document.getElementById(objId).innerHTML = "some text we like";
我要做的是更新现有文本的子集,要替换的目标由隐藏标签标识。因此,例如,不必在我自己的代码中解析这样的东西:
<p> Here's a huge block of text, many lines long and
**here's the part I want to update,** buried within it and yet there's even more afterwards.</p>
...相反,我想(并且可以)做这样的事情:
<p> Here's a huge block of text, many lines long and <option id="target">**here's the part I want to update,**</option> buried within it and yet there's even more afterwards.</p>
...然后更新为:
document.getElementById("target").innerHTML = "replacement text we like";
不出所料,这行得通,但是,它具有添加换行符的效果,就好像在 <option>
和 </option>
.[=19= 的地方有一个 <br>
标签一样]
这是该调用的有效结果:
<p> Here's a huge block of text, many lines long and<br> replacement text we like<br> buried within it and yet there's even more afterwards.</p>
如何在不插入换行符的情况下执行此操作?
您可以使用 <span>
标签而不是 <div>
来做到这一点。这是一个有效的 JSFiddle.
像<option>
或<div>
这样的元素是块元素。您需要使用内联元素,以便可以使用 <span>
而不是 <option>
:
function myFoo() {
document.getElementById("target").innerHTML = "replacement text we like";
}
<p> Here's a huge block of text, many lines long and <span id="target">**here's the part I want to update,**</span> buried within it and yet there's even more afterwards.</p>
<button id="btn" onclick="myFoo()">Change Text!</button>