-2

我有很多跨度列表,例如

<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

4 回答 4

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 小提琴演示

要删除所有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 小提琴演示

使用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 小提琴演示

或者:

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 小提琴演示

参考:

于 2013-07-11T11:15:44.103 回答
1

香草 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/

于 2013-07-11T11:10:18.367 回答
1

在这里演示

 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++;
    };
于 2013-07-11T11:39:53.127 回答
0

你为什么不为此使用 JQuery。为所有相关标签分配一个类,如“class="deactiveSpan"”,并将一个跨度元素分配为 class="activeSpan"。现在,您可以使用 jQuery 获取这两种类型的元素并轻松处理它。

于 2013-07-11T11:24:01.947 回答