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

时间:2012-01-06 12:45:30

标签: javascript dom

在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兄弟”?

2 个答案:

答案 0 :(得分:1)

您可以遍历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");

<强> Example on jsfiddle

答案 1 :(得分:0)

我强烈建议使用像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/

相关问题