2017-05-30 55 views
0

我有按鈕上用onclick:jQuery的觸發與通話功能

<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?

+0

'document.querySelector(validSelctor)。點擊( )' – Satpal

+0

它會工作,如果你有ID傳遞給你的元素'cityName' – Omi

回答

2

嘗試:

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

你的代碼工作正常,除非你沒有用元素爲default ID。 否則你的代碼就會突破&給予誤差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>