更改包含其他元素的元素的文本

Change text of element that contains other elements

本文关键字:元素 文本 其他 包含      更新时间:2023-09-26

我有这样的标记:

<li data-id="1">
  <button type="button" class="btn btn-default btn-md" style="margin: .25em; padding: .25em;">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    random text
    <input type="hidden" name="global_filter[default_fields][][apple]" value="random text_again">
  </button>
</li>

我想把文本"随机文本"改为"其他内容"。

我能够找到文本节点:

  $li.find('button').first().contents().filter(function() {
    return this.nodeType == 3;
  }).text();

但是我怎样才能更改文本?当我将参数传递给像text('something else')这样的文本时,没有任何变化。

我可能会把文本放在自己的容器中,比如

<div id='changeableText'>Random Text</div>

然后直接用访问

$('#changeableText').text('New text!');

以实现这一点。

更新

您可以选择按钮的text()并更改它。

注意:如果存在多个未标记的文本,这将不起作用。例如

<li data-id="1">
  <button type="button" class="btn btn-default btn-md" style="margin: .25em; padding: .25em;">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    random text
    <input type="hidden" name="global_filter[default_fields][][apple]" value="random text_again">
    another random text
  </button>
</li>

否则她就是工作演示:

var getNonMarkedUpText = $('button').text().replace(/^'s+|'s+$|'s+(?='s)/g, "");
$('button').html($('button').html().replace(getNonMarkedUpText, 'something else'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li data-id="1">
  <button type="button" class="btn btn-default btn-md" style="margin: .25em; padding: .25em;">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    random text
    <input type="hidden" name="global_filter[default_fields][][apple]" value="random text_again">
  </button>
</li>

试试这个:

<li data-id="1">
  <button type="button" class="btn btn-default btn-md" style="margin: .25em; padding: .25em;">
    <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
    <span id="txt1">random text</span>
    <input type="hidden" name="global_filter[default_fields][][apple]" value="random text_again">
  </button>
</li>

这样,你就可以去:

document.getElementById("txt1").innerText = "txet modnar";

$("#txt1").text("tandom rext");