Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/449.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 获取动态创建的select子元素的属性_Javascript_Jquery - Fatal编程技术网

Javascript 获取动态创建的select子元素的属性

Javascript 获取动态创建的select子元素的属性,javascript,jquery,Javascript,Jquery,我有一个动态创建的select元素。我如何才能获得所选特定选项的属性。现在它只给了我第一个元素的att 这是我的密码 $('button').click(function(){ var arena = $(this).attr('id'); var id = arena + '.jpg'; $('#header').css('background-image', 'url('+id+')'); $('#chooseArena

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

这是我的密码

    $('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);
    });
$(“按钮”)。单击(函数(){
var arena=$(this.attr('id');
var id=arena+'.jpg';
$('#header').css('background-image','url('+id+'));
$('#choosarena').html(“+”选择你的忍者\
\
黑色的\
绿色的\
\
\
黑色的\
绿色的\
");
});
$(文档).on('change','select',函数(e){
var ninja1=$(e.target).children().attr('id');//这始终返回第一个attr。我应该如何使其返回选定的子元素。
警报(ninja1);
});

使用伪类选择器在上下文中获取所选选项

$(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);
});

我认为选项不能有id属性。您是否可以使用var ninja1=$(e.target.children().val();相反