单击查找数据属性 - Jquery

时间:2017-07-16 18:37:52

标签: javascript jquery html

我点击按钮删除隐藏的课程。但它是一个动态列表,我只想打开其中一个选项。这是我的HTML

HTML:

   <% @assignments.each do |assignment| %>
     <div class="assignments__index__card">

      <div class="assignments__index__options">
        <i class="fa fa-list-ul" aria-hidden="true" data-assignment="<%= assignment.id %>"></i>

        <ul class="assignments__index__options__index <%= assignment.id %> hidden">
          <li><%= link_to "Remove", account_assignment_path(assignment), method: :delete %></li>
          <li><%= link_to "Edit", account_assignments_path %></li>
        </ul>
      </div>
    </div>
  <% end %>

这是我的JS

JS

window.dashboard = {
  sel: {
    dropdown: $(".fa-list-ul")
  },

  init: function() {
    var _this = this;

    $(document).on("click", _this.sel.dropdown, function(event) {
      debugger;
      $(".assignments__index__options__index").removeClass("hidden")
      $("body").addClass("openDropdown")
      event.preventDefault();
    });

    $(document).on("click", "body.openDropdown", function(event) {
      $(".assignments__index__options__index").addClass("hidden")
      $("body").removeClass("openDropdown")
      event.preventDefault();
    });
  }
};

dashboard.init();

这个问题是我需要将赋值的数据传递给Javascript

正如您在单击此类fa-list-ul时所看到的,我想查找该类的数据。但这在点击功能中不起作用:

$(this).data("assignment")

如何从点击功能中获取此属性的数据?

1 个答案:

答案 0 :(得分:2)

您可以更改此行:

$(document).on("click", _this.sel.dropdown, function(event) {

为:

$(document).on("click", '.fa-list-ul', function (event) {

window.dashboard = {
  sel: {
    dropdown: $(".fa-list-ul")
  },

  init: function() {
    var _this = this;

    $(document).on("click", '.fa-list-ul', function(event) {
      console.log($(this).data('assignment'));
      $(".assignments__index__options__index").removeClass("hidden")
      $("body").addClass("openDropdown")
      event.preventDefault();
    });

    $(document).on("click", "body.openDropdown", function(event) {
      $(".assignments__index__options__index").addClass("hidden")
      $("body").removeClass("openDropdown")
      event.preventDefault();
    });
  }
};
dashboard.init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div class="assignments__index__card">

  <div class="assignments__index__options">
    <i class="fa fa-list-ul" aria-hidden="true" data-assignment="<%= assignment.id %>">CLICK HERE</i>

    <ul class="assignments__index__options__index <%= assignment.id %> hidden">
      <li>
        <%= link_to "Remove", account_assignment_path(assignment), method: :delete %>
      </li>
      <li>
        <%= link_to "Edit", account_assignments_path %>
      </li>
    </ul>
  </div>
</div>