我有 HTML 下拉列表,想要在更改下拉项目时打印简单的控制台文本。我使用以下代码:
$('.pm').on('change', "select[name='pay']:", function() {
console.log("Hello World");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pm">
<select name="pay">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
</div>
&#13;
我想点击A时会发出A&#39; A&#39;在控制台上,点击B给出&#39; B&#39;在控制台.. 或点击任何选项给出 控制台上的 HELLO WORLD
答案 0 :(得分:3)
使用$(this).val()
获取所选选项的选定值。
<强>演示强>
$('.pm').on('change', "select[name='pay']", function() {
console.clear();
console.log("selected is " + $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pm">
<select name="pay">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
</div>
答案 1 :(得分:0)
请尝试以下代码:
$('select[name="pay"]').on('change', function () {
console.log($(this).val());
console.log("Hello World!");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pm">
<select name="pay">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
</div>
&#13;
答案 2 :(得分:0)
jQuery('select[name="pay"]').on('change', function () {
console.log("Hello World");
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="pm">
<select name="pay">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
</div>
&#13;
答案 3 :(得分:0)
// Use this script
//$(this).val() gives the value of option selected, not the text.
$(document).ready(function(){
$('select[name=pay]').change(function() {
console.log($(this).find('option:selected').text());
});
});