获取Dropdown的名称或ID

时间:2014-03-19 14:51:09

标签: jquery

我有五个下拉菜单,当有一个更改时,我想更新其他下拉列表中的选项列表。目前我正在使用下面的代码。现在我只是显示字符串。一旦我使这部分工作,我将把字符串传递给另一个页面,该页面将运行一些查询以获取其他下拉列表的新值列表,然后重建下拉列表。我愿意接受有关我的方法的建议,但目前这是我的障碍:如何获取下拉列表的名称(或ID)。我使用.each是为了简洁,因为我知道我可以使用五个选择器的名称和ID,但我认为这更好。

$("select").change(function() {
    var str = "";
    $("select option:selected").each(function() {
        str += $(this).attr('name') + " ";
        str += $(this).text() + " ";
    });
    window.alert(str);
}).change();

此外,此代码会在最初构建下拉列表时触发。我该如何预防呢?所以我的问题是如何获得名称或ID?在这里尝试$(this).attr('name')。如何在第一次构建下拉列表时阻止它运行?有没有更好的方法来重建下拉列表?

工作代码

$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
    str += $(this).parent().attr('id') + " ";
    str += $(this).text() + " ";
});
window.alert(str);
});

jsFiddle

2 个答案:

答案 0 :(得分:0)

首先,您在添加处理程序后触发了该事件。 事件定义后删除.change();

其次,您想获取下拉列表的ID(来自所选选项吗?),这样您就可以获得$(this).parent().attr('id')$(this).parent().id;

- 如果不是来自所选的选项 - $(this).id就可以了。

     $("select")
            .change(function() {
                var str = "";

                    alert($(this).id); //select id

                     $(this).find('option').each(function() {
                        str += $(this).attr('name') + " ";

                        alert($(this).parent().id); //select id..

                        str += $(this).text() + " ";
                     });
                 window.alert(str);
            });

答案 1 :(得分:0)

这样的东西?

演示:JSFiddle

HTML

<select name="s1" id="ss1"><option value="1">ONE</option><option value="2">TWO</option></select>
<select name="s2" id="ss2"><option value="1">ONE</option><option value="2">TWO</option></select>
<select name="s3" id="ss3"><option value="1">ONE</option><option value="2">TWO</option></select>
<select name="s4" id="ss4"><option value="1">ONE</option><option value="2">TWO</option></select>
<select name="s5" id="ss5"><option value="1">ONE</option><option value="2">TWO</option></select>

JS

$(function(){
    $('select').change(function() {
        var str = "";
        $('select').each(function(i){
            str += "id: " + this.id + "\n";
            str += "name: " + $(this).attr("name") + "\n\n\n";
        });
        alert (str);
    });
});