如何在更改功能文档中引用“ $(this)”?

时间:2018-07-17 13:37:35

标签: jquery

我正在使用.on更改文档来检测动态创建的下拉菜单的更改,并且需要从所选选项中访问属性。到目前为止,我有这个:

$(document).on('change', 'select', function(event) {
    //Target the chosen option
});

但是使用典型的$(this)选择器在这里无法使用。如何获取所选的选项?

编辑:我发现了这个类似的问题,但是它没有说明如何寻找选定的问题并获得某些属性jQuery get value of select onChange

3 个答案:

答案 0 :(得分:0)

将on change事件应用于选择中的类。不管有多少选择,现在已更改的选择就是this选择器。

$(document).on("change", "select", function() {
    var valueOfSelect = $(this).val();
    alert(valueOfSelect)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="dropdowns">
  <option value="1">Hey</option>
  <option value="2">how</option>
  <option value="2">are</option>
  <option value="3">you</option>
</select>

<select class="dropdowns">
  <option value="10">Hey</option>
  <option value="20">how</option>
  <option value="30">are</option>
  <option value="40">you</option>
</select>

答案 1 :(得分:0)

我尝试使用您的代码,$this正常工作。

$(document).on("change", "select", function() {
    $(this).val();
})

看看我的JSFiddle:https://jsfiddle.net/ogf4rzw6/11/

答案 2 :(得分:-1)

// Set a timeout for this function to run after the dynamic select has been populated (this is optional if you need a second for your dynamic content to render)
setTimeout(function(){
    // Loop throough all select fields, you can adjust this to target a single select by class or ID
    $('select').each(function(index){  
        // Set the field variable to a matched select input
        var field = $(this);
        // Set the fieldId variable for the select input ID
        var fieldId = $(this).attr('id');
        // Set the SelectedText variable to store our selected option's text
        var selectedText = $(field).find(":selected").text();
        // Set the SelectedValue variable to store our selected option's value
        var selectedValue = $(field).find(":selected").text();
        // Console log our results and do anything we want with them below
        console.log('Current selected text is ' + selectedText + ' and the value is ' + selectedValue + ' belonging to Select ID ' + fieldId);
    });
    // end the timeout delay, again this is optional you may not need SetTimeout at all or you may not need to loop through all selects, you can target a single one instantly or on call
}, 1000);