表单上有一个按钮,单击该按钮可提供一些各种类型的下拉菜单。准备好表单后,如何在这些类型的任何一个上引发点击事件?

这是我尝试过的方法,但是不起作用。

<script>
    $( document ).ready(function() {
        document.getElementsByClassName("advanced-search-add-text-row").click();
    });
</script>

  <div class="btn-group">
    <a class="btn btn-success dropdown-toggle advanced-search-add-row-dropdown" data-toggle="dropdown" href="#">
      <span class="glyphicon glyphicon-plus glyphicon-white"></span>
      <span class="caret"></span>
    </a>
    <ul class="dropdown-menu pull-right">
      <li><%= link_to I18n.t("advanced_search.type.text"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-text-row", "data-type" => "text" %></li>
      <li><%= link_to I18n.t("advanced_search.type.date"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-date-row", "data-type" => "date" %></li>
      <li><%= link_to I18n.t("advanced_search.type.boolean"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-bool-row", "data-type" => "boolean" %></li>
        <li><%= link_to I18n.t("advanced_search.type.controlled_value"), "javascript:void(0)", :class => "advanced-search-add-row advanced-search-add-enum-row", "data-type" => "enum" %></li>
    </ul>
  </div>


用于创建行的javascript:

  $advancedSearchContainer.on("click", ".advanced-search-add-row", function(event) {
    event.stopPropagation();
    event.preventDefault();

    var index = $("input[id^='v']", $advancedSearchRowContainer).length;

    var adding_as_first_row = false;
    if (index == 0) {
      adding_as_first_row = true;
    }

    while ($(":input[name='f"+index+"']", $advancedSearchContainer).length > 0) {
      index += 1;
    }

    addAdvancedSearchRow(index, $(this).data("type"), adding_as_first_row, {});

    // hide the drop down menu after clicking an option
    $(this).closest(".dropdown-menu").siblings(".advanced-search-add-row-dropdown").trigger("click");
  });

最佳答案

getElementsByClassName返回HTMLCollection

因此更改行:

document.getElementsByClassName("advanced-search-add-text-row").click();


至:

document.getElementsByClassName("advanced-search-add-text-row")[0].click();


相反,使用jQuery可以编写:

$(".advanced-search-add-text-row").trigger('click');

关于javascript - 如何引起点击事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39707183/

10-11 09:08