带调用函数的Jquery触发器

时间:2017-05-30 15:07:32

标签: javascript jquery html

我有onclick按钮:

 <button   class="tablinks" onclick="openDiv(event, 'default')">{'TEXT_DEFAULT_SETTINGS'|tr}</button>

openDiv功能:

function openDiv(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;
  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

如何触发此onclick?

2 个答案:

答案 0 :(得分:2)

尝试:

document.getElementsByClassName("tablinks")[0].click()

答案 1 :(得分:1)

你的代码工作正常,除非你没有default作为id的元素。 否则你的代码会破坏&amp;为此语句Uncaught TypeError: Cannot read property 'style' of null

提供document.getElementById(cityName).style.display = "block";错误

请参阅以下代码的工作示例:

function openDiv(evt, cityName) {
  // Declare all variables
  var i, tabcontent, tablinks;
  // Get all elements with class="tabcontent" and hide them
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  // Get all elements with class="tablinks" and remove the class "active"
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }

  // Show the current tab, and add an "active" class to the button that opened the tab
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}
#default {
display:none
}
 <button   class="tablinks" onclick="openDiv(event, 'default')">{'TEXT_DEFAULT_SETTINGS'|tr}</button>

<div id="default">
This is a default div
</div>