替换输入标记之前或之后的文本标签

Replace Text label before or after input tag

本文关键字:或之后 文本标签 输入 替换      更新时间:2023-09-26

在HTML中,我有一些带有标签的输入标签:

<label>Address <input type="text" name="address" /></label>
<label><input type="text" name="surname" /> Surname</label>

我想用javascript函数更改标签文本
我知道这是可能的,例如

input_name.parentNode.firstChild.nodeValue = "New label text";

不幸的是,标签既在输入之前又在输入之后。所以firstChild和lastChild一样。

我知道可以将标签放入<span>并使用getElementById。但我不喜欢
也许还可以在标签中添加idfor。。。但我不喜欢。

如何有效地替换"输入之前或之后的第一个TextNode同级"?

您可以遍历childNodes,找到TEXT_NODE的第一个实例并替换文本。

var replaceText = function(inputName, newText) {
    var TEXT_NODE = 3, 
        input_name = document.getElementsByName(inputName)[0], 
        nodes = input_name.parentNode.childNodes;
    for (i = 0; i < nodes.length; i++) {
        if (nodes[i].nodeType === TEXT_NODE) {
            nodes[i].nodeValue = newText;
            break;
        }
    }
};
replaceText("address", "Not an Address");
replaceText("surname", "Not a Surname");

jsfiddle上的示例

我强烈建议使用像JQuery这样的跨浏览器框架,而不是使用原始Javascript。然后使用Jquery:

$('input').bind("keyup", function(event) {
    var textNodes = $(this).parent().contents().filter(function() {
        return this.nodeType == Node.TEXT_NODE;
    });
    textNodes.each(function() { this.nodeValue = "bla"; });
});

应该有效!此处演示:http://jsfiddle.net/Hh33v/6/

请参阅http://api.jquery.com/filter/和http://api.jquery.com/contents/