使用Javascript提供Span ID(ONE BY ONE)

时间:2013-07-11 11:03:48

标签: javascript dom

我有很多跨度列表,比如

<span id="current"> hello </span>
<span> is </span>
<span> anyone </span>
<span> here</span>

我正在使用JavaScript执行操作

document.onkeypress = function(evt) {
};

我希望我的span id="current"消失和下一个元素,<span> is </span>获得id="current"

4 个答案:

答案 0 :(得分:1)

Vanilla JavaScript:

document.onkeypress = function( e ) {
    var
        outboundEl = document.getElementById('current'),
        nextEl = outboundEl.nextElementSibling;

    // remove the #current element from the DOM but keep a reference to it
    outboundEl = outboundEl.parentNode.removeChild(outboundEl);

    // make sure we only grab a reference to a span
    if( nextEl && nextEl.tagName.toLowerCase() === 'span' ) {
        nextEl.id = outboundEl.id;
    }
};

以下是演示:http://jsfiddle.net/PSgQ2/

答案 1 :(得分:1)

我建议:

function idProgress (e) {
    var self = this,
        id = self.id,
        next = self.nextElementSibling;
    if (next === null) {
        // this assumes you don't want to remove the last element
        return false;
    }
    else {
        self.parentNode.removeChild(self);
        next.id = id;
        next.addEventListener(e.type, idProgress);
    }
}

var span = document.getElementById('current');
span.addEventListener('click', idProgress);

JS Fiddle demo

要删除所有span元素,请点击(包括最后一个):

function idProgress (e) {
    var self = this,
        id = self.id,
        next = self.nextElementSibling;
    self.parentNode.removeChild(self);
    if (next !== null) {
        next.id = id;
        next.addEventListener(e.type, idProgress);
    }
}

var span = document.getElementById('current');
span.addEventListener('click', idProgress);

JS Fiddle demo

使用keypress而不是click(我在第一次阅读问题时忽略了这一点):

function idProgress (e) {
    var self = this.getElementById('current'),
        id = self.id,
        next = self.nextElementSibling,
        key = e.which;

    if (key !== 110 || next === null) {
        return false;
    }
    else {
        self.parentNode.removeChild(self);
        next.id = id;
    }
}

document.addEventListener('keypress', idProgress);

JS Fiddle demo

或者:

function idProgress(e) {
    var self = this.getElementById('current'),
        id = self.id,
        next = self.nextElementSibling,
        key = e.which;
    if (key == 110) {
        self.parentNode.removeChild(self);
        if (next !== null) {
            next.id = id;
        }
    }
}

document.addEventListener('keypress', idProgress);

JS Fiddle demo

参考文献:

答案 2 :(得分:1)

  

DEMO HERE

 var i = 1;
    document.onkeypress = function (evt) {

        var element = document.getElementById('current');
        alert(element.textContent);
        var sibling = element.parentNode.children;
        element.attributes.id.nodeValue = "newId" + i;
        sibling[i].id = "current";
        i++;
    };

答案 3 :(得分:0)

为什么不使用JQuery呢?将类分配给所有相关标签,例如'class =“deactiveSpan”',并将一个span元素指定为class =“activeSpan”。现在,您可以使用jQuery轻松获取两种类型的元素并进行处理。