简体   繁体   English

如何使用 jquery 获取所选引导程序下拉项的值?

[英]How do I get the value of a selected bootstrap dropdown-item using jquery?

I have the following bootstrap dropdown.我有以下引导程序下拉列表。

I try to get into the console.log the value of the selected dropdown-item with jquery.我尝试使用 jquery 进入 console.log 所选下拉项的值。 I can console.log the text, using the below code but for some reason when I change .text() to .val() , I don't get the value/我可以使用下面的代码 console.log 文本,但是由于某种原因,当我将.text()更改为.val() ,我没有得到值/

 $('.dropdown-item').click(function() { console.log( $(this).text() ); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action='/' method='get'> <div class="dropdown"> <button class="btn btn-primary dropdown-toggle btn-sm" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select Date </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#" value="1">March 16 to 19 - CANCELLED</a> <a class="dropdown-item" href="#" value="2">March 21 and 22 - REVISED</a> <a class="dropdown-item" href="#" value="3">March 23 to 26 - REVISED</a> <a class="dropdown-item" href="#" value="4">March 28 and 29</a> <a class="dropdown-item" href="#" value="5">March 30 to April 2 - REVISED</a> </div> </div> </form>

https://jsfiddle.net/vkLr7zhe/ use data attribute as solution . https://jsfiddle.net/vkLr7zhe/使用数据属性作为解决方案。 I put in fiddle我把小提琴

$('.dropdown-item').click(function() {
  console.log( $(this).data("id") );
});






<a class="dropdown-item"data-id="1" href="#" value="1">March 16 to 19 - CANCELLED</a>

Looks like I had to use the .attr method like below.看起来我必须使用如下所示的 .attr 方法。 Thank you to @KevynKlava for the answer感谢@KevynKlava 的回答

$('.dropdown-item').click(function() {
  console.log( $(this).attr('value') );
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM