简体   繁体   English

从生成的引导程序下拉菜单中查找下拉项

[英]Find dropdown-item from generated bootstrap dropdown-menu

I have a dynamically generated bootstrap .dropdown-menu and I cannot target the .dropdown-item child class.我有一个动态生成的引导程序.dropdown-menu ,我无法定位.dropdown-item子 class。

I want to be able to toggle a class on each specific .dropdown-item when a user clicks on it.当用户单击它时,我希望能够在每个特定的 .dropdown-item上切换 class 。

The html looks like this after is dynamically generated:动态生成后的 html 如下所示:

<div class="dropdown-menu">
 <label class="dropdown-item">
  <input type="checkbox" data-field="name" value="1" checked="checked">
  <span>name</span>
 </label>

 <label class="dropdown-item">
  <input type="checkbox" data-field="price" value="2" checked="checked">
  <span>price</span>
 </label>

 <label class="dropdown-item">
  <input type="checkbox" data-field="column1" value="3" checked="checked">
  <span>column 1</span>
 </label>
</div>

I have tried targeting it directly with:我试过直接用它来定位它:

$(".dropdown-item").click(function(){
 $(this).toggleClass("item-selected");
});

but it doesn't work.但它不起作用。

I read in an answer here: jquery selecting dynamic class id inside dynamically created div , that I needed to delegate with newly created elements and so I am able to target the dynamically generated .dropdown-menu with:我在这里读到了一个答案: jquery 在动态创建的 div 中选择动态 class id ,我需要使用新创建的元素进行委托,因此我可以将动态生成的 .dropdown-menu定位为:

$(document).on('change',"[class*=dropdown-menu]", function() {
 alert("You clicked on a .dropmenu-item!");
 $(this).children(".dropdown-item").toggleClass("item-selected");
});

Clicking on each .dropdown-item toggles the class on all items.单击每个.dropdown-item会在所有项目上切换 class。

I would like to only toggle the class on the specific .dropdown-item the user is clicking on我只想在用户单击的特定.dropdown-item上切换 class

https://codepen.io/makloon/pen/mdboxEb https://codepen.io/makloon/pen/mdboxEb

Thanks in advance for any advice提前感谢您的任何建议

Try this:尝试这个:

// Initialize all to selected, since that's the default state.
$('.dropdown-item').addClass('item-selected');

// Use `mousedown` since Bootstrap Tables prevents propagation of `click`.
$('.dropdown-item').on('mousedown', function(e) {
  // This runs _before_ the checkbox is checked/unchecked.
  if ($(this).find('input').is(':checked')) {
    $(this).removeClass("item-selected");
  } else {
    $(this).addClass("item-selected");
  }
});

Working example: https://codepen.io/mac9416/pen/yLBwKKv工作示例: https://codepen.io/mac9416/pen/yLBwKKv

The problem is that Bootstrap Tables prevents propagation of the click event.问题是引导表阻止了click事件的传播。 So we have to listen for an event that happens earlier - namely, mousedown .所以我们必须监听一个更早发生的事件——即mousedown

And instead of using toggleClass , I've set it up to explicitly use the state of the checkbox.我没有使用toggleClass ,而是将其设置为明确使用复选框的 state 。

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

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