【问题标题】:Get the attr of a dynamically created select child element [duplicate]获取动态创建的选择子元素的属性[重复]
【发布时间】:2017-06-05 20:22:01
【问题描述】:

我有一个动态创建的选择元素。我将如何获得所选特定选项的属性。现在它只是给了我第一个元素的属性。

这是我的代码

    $('button').click(function(){
        var arena = $(this).attr('id');
        var id = arena + '.jpg';
        $('#header').css('background-image', 'url('+id+')');
        $('#chooseArena').html("" + "<h1>Pick your ninja</h1>\
            <select name='first'>\
                <option id = 'black' value='black.png'>Black</option>\
                <option id = 'green' value='green.png'>Green</option>\
            <select>\
            <select name='second'>\
                <option value='black.png'>Black</option>\
                <option value='green.png'>Green</option>\
            <select>");

    });
    $(document).on('change', 'select', function(e){
        var ninja1 = $(e.target).children().attr('id'); //this always returns the first attr.  What should I do to get this to return the child element selected.
        alert(ninja1);
    });

【问题讨论】:

  • 我认为选项不能有 id 属性。你能用 var ninja1 = $(e.target).children().val();代替?

标签: javascript jquery


【解决方案1】:

使用:selected 伪类选择器在上下文中获取选定的选项。

$(document).on('change', 'select', function(e){
    var ninja1 = $('option:selected', this).attr('id'); //this always returns the first attr.  What should I do to get this to return the child element selected.
    alert(ninja1);
});

【讨论】:

    猜你喜欢
    • 2014-10-21
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 2014-07-06
    • 1970-01-01
    • 2022-07-06
    • 2013-01-20
    • 2013-10-25
    相关资源
    最近更新 更多