如何引发点击事件?

时间:2016-09-26 15:50:35

标签: javascript ruby-on-rails

表单上有一个按钮,点击它时会提供一些不同类型的下拉列表。当表单准备就绪时,如何在任何这些类型上引发click事件?

这是我尝试过的,但是没有用。

<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");
  });

2 个答案:

答案 0 :(得分:0)

getElementsbyClassName返回一个数组!而且你不能在整个数组上执行click函数,你需要点击每个元素:

ViewFlipper

答案 1 :(得分:0)

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');