jQuery - 仅设置元素的文本而不删除其他元素(锚点) [英] jQuery - setting an element's text only without removing other element (anchor)

查看:118
本文介绍了jQuery - 仅设置元素的文本而不删除其他元素(锚点)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的元素:

<td>
  <a>anchor</a>
  [ some text ]
</td>

我需要在jQuery中设置它的文本,而不删除锚点。

And i need to set it's text in jQuery, without removing the anchor.

元素的内容可能会有所不同(文本在之前或之后),实际文本是未知的。

The element's contents could vary in order (text before or after), and the actual text is unknown.

谢谢

新的更新

这就是我使用的,只假设一个文本节点:

This is what i came up using, assumes only a single text node:

    function setTextContents($elem, text) {
        $elem.contents().filter(function() {
            if (this.nodeType == Node.TEXT_NODE) {
                this.nodeValue = text;
            }
        });
    }

    setTextContents( $('td'), "new text");


推荐答案

Neal的回答是我的建议。 jQuery没有办法选择文本节点如何选择文本使用jQuery的节点?

Neal's answer is my suggestion. jQuery doesn't have a way to select text nodes How do I select text nodes with jQuery?.

更改HTML结构将构成最简单的代码。如果你不能这样做,你可以使用childNodes属性寻找类型3的节点(TEXT_NODE)

Changing your HTML structure will make for the simplest code. If you can't do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)

这里有一些示例代码,假设最后一个节点是您要编辑的节点。这是一种比替换td的整个内容更好的方法,因为在重新创建HTML时可能会丢失事件处理程序

Here's some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML

$('a').click(() => console.log('<a> was clicked'))

$('#btn').click(() =>
  $('.someClass').get(0).lastChild.nodeValue = " New Value");

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='someClass'>
  <a href="javascript:void(0)">anchor</a> [ some text ]
</div>

<button id='btn'> Change text without losing a tag's handler</button>

这篇关于jQuery - 仅设置元素的文本而不删除其他元素(锚点)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆