简体   繁体   English

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

[英]Select element with jQuery without using ID

So I have a list of elements in an array. 所以我有一个数组中的元素列表。 I'd like to add a jQuery toggle event to each element and pass in two functions as parameters. 我想向每个元素添加一个jQuery切换事件,并传入两个函数作为参数。 This is what I have so far, though it's giving me errors, saying that e (the Event Object) is undefined inside moveToSelected and moveToUnselected. 到目前为止,这就是我所能得到的,尽管它给了我错误,说在moveToSelected和moveToUnselected内部未定义e(事件对象)。

// 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, as requested: 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>

Thanks for the help! 谢谢您的帮助!

Uhm, why aren't you using jQuery, this is already built in ? 嗯,你为什么不使用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 小提琴

The vanilla javascript solution for future viewers. 适用于未来观众的香草javascript解决方案。 No jQuery required. 无需jQuery。 This is effectively the same script as the accepted answer, without all the overhead of 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);
            }
        };
    }
})();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM