使用jQuery选择元素而不使用ID

时间:2015-05-22 21:18:20

标签: javascript jquery toggle

所以我有一个数组中的元素列表。我想为每个元素添加一个jQuery toggle事件,并将两个函数作为参数传递。这是我到目前为止所做的,虽然它给了我错误,说e(事件对象)在moveToSelected和moveToUnselected中是未定义的。

// Getting my array
var selected = document.getElementsByClassName("selected_style");

// The two functions to toggle between:

function moveToSelected(e) {
    style = e.target;
    style.className = "selected_style";
    $('#selected-style').append(e.target);
}

function moveToUnselected(e) {
    style = e.target
    style.className = "unselected_style";
    $('#unselected-style').append(e.target);
}

// Going through the array and adding a toggle event to each element.
for(var i = 0; i < selected.length; i++) {
    var element = $(unselected[i]);
    element.toggle(moveToSelected, moveToUnselected);
}

HTML,按要求:

<ul id="selected-style">
    <li>
      Some Style
    </li>
    <li class="selected_style">
      Style
    </li>
    <li class="selected_style">
      Style
    </li>
    <li class="selected_style">
      Style
    </li>
</ul>

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

嗯,你为什么不使用jQuery,这已经内置了?

$('.selected_style').on('click', function() {
    $(this).toggleClass('selected_style unselected_style');

    if ( $(this).hasClass('selected_style') ) {
        $('#selected-style').append(this);
    } else {
        $('#unselected-style').append(this);
    }
});

FIDDLE

答案 1 :(得分:1)

面向未来观众的vanilla javascript解决方案。不需要jQuery。这实际上是与接受的答案相同的脚本,没有jQuery的所有开销。

Demo

(function () {
    "use strict";
    var selected = document.getElementById('selected-style');
    var unselected = document.getElementById('unselected-style');
    var items = document.querySelectorAll('.selected_style'), item;
    for (var i = 0; item = items[i]; i++) {
        item.onclick = function(){
            if(this.className.indexOf('unselected_style') >= 0) {
                this.className = this.className.replace(' unselected_style','');
                this.className += ' selected_style';
                selected.appendChild(this);
            } else {
                this.className = this.className.replace(' selected_style','');
                this.className += ' unselected_style';
                unselected.appendChild(this);
            }
        };
    }
})();