jQuery - 循环遍历每个元素

时间:2015-07-09 09:34:41

标签: jquery

我有一个脚本可以将选定的选项从下拉列表转换为链接。

每个下拉列表都包含在<li>中 - 并且可以通过我的脚本添加无限制的重复项,因此很难为每个<li>提供一个ID选择器。

HTML:

<ul class="mylist">
    <li>
        <select>
            <option value="http://google.com">Google</option>
            <option value="http://twitter.com">Twitter</option>
        </select>
    </li>
</ul>

我的部分脚本负责添加更多重复项并将下拉列表转换为链接。

$(document).keydown(function (e) {
    var key = e.which;
    if(key == 107) {
        $('.mylist').append("<li><select><option value='http://google.com'>Google</option><option value='http://twitter.com'>Twitter</option></select></li>");
    }
});

$("button").click(function () {
    var which = $("select").val();
    var text = $('select option:selected').html();
    $("select").replaceWith("<a href='" + which + "'>" + text + "</a>");
});

我需要更改我的脚本,以便将EACH下拉列表<select>转换为EACH选定值,因为现在它将每个下拉列表转换为第一个下拉列表的值。如果我没有id选择器,我该怎么做呢,因为可以添加无限制的重复项?

4 个答案:

答案 0 :(得分:2)

使用jQuery.each()

$("button").click(function () {
    $("select").each(function() {
        var value = $(this).val();
        var text = $(this).find('option:selected').html();
        $(this).replaceWith("<a href='" + value + "'>" + text + "</a>");
    });
});

答案 1 :(得分:1)

使用.each()功能。

$("select").each(function (index, value) {
    // ...
});

答案 2 :(得分:1)

尽管jQuery提供的每个函数与原生的javascript for循环相比相对较慢,但你应该避免使用它。 Native for循环速度提高了100倍。您可以使用本机函数和eq()来获取循环中的某些元素。

var select = $("select");
$("button").click(function () {
    for (var i = 0; i < select.length; i++) {
        var value = select.eq(i).val();
        var text = select.eq(i).find('option:selected').html();
        select.eq(i).replaceWith("<a href='" + value + "'>" + text + "</a>");
    });
});

答案 3 :(得分:1)

答案很简单,但有很多方法可以优化它。

因此假设$("button")指的是稍后出现的某个按钮(你应该给它一个ID或类并引用btw),你可以这样做:

//Document ready adds closure
$(document).ready(function () {
    var $mylist = $('.mylist');
    //Place event handler on body or even $mylist to reduce polling processing (compared to entire document)
    //Use 'keyup' instead of 'keydown' since it won't fire continuously if held down
    $('body').on('keyup', function (e) {
        var template = $('<li><select><option value="http://google.com">Google</option><option value="http://twitter.com">Twitter</option></select></li>');
        //If key pressed is '+' symbol - 107 is keypad '+', 187 is keyboard '+'
        if(e.which === 107 || e.which === 187) {
            //Since $('.mylist') is the never-changing container, it's better to cache the variable globally and reference it on every keypress
            $mylist.append(template);
        }
    });

    $('button').on('click', function () {
        $("select").each(function (index, el) {
            //.children() is a little bit less intensive than .find()
            var $select = $(el),
                $selectedOption = $select.children('option:selected'),
                selectedValue = $selectedOption.val(),
                selectedText = $selectedOption.text(),
                replacementLink = $('<a href="' + selectedValue + '">' + selectedText + '</a>');

            //Replace select with link
            $select.replaceWith(replacementLink);
        });
    });
});

对于此实例中的选定选项文本,最好使用.text()而非.html(),因为它会减少XSS漏洞(停止潜在的用户输入反射),并从缓存变量中获取属性是表现好一点。

还有一件事:如果你要为选择本身添加任何事件处理,你需要像现在这样“实时”来考虑以后添加的选择:

$mylist.on('change', 'select', function (changeEvent) {
    //whatever
});
祝你好运!