Javascript Squarespace click()函数不起作用

时间:2018-10-26 22:21:42

标签: javascript squarespace

以下代码不适用于Squarespace。选项卡显示得很好,单击它们就可以了,我只是无法让javascript的最后一行能够正常加载其中一个选项卡。

我已经将HTML注入为代码块,标头中的JS和自定义css部分中的css。我对如何使其工作有些迷茫,它在控制台中的工作原理没问题。

function openCity(evt, cityName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
.tab {
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Style the buttons inside the tab */
.tab button {
    background-color: inherit;
    float: left;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of buttons on hover */
.tab button:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
.tab button.active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}
<div class="tab">
  <button class="tablinks"  onclick="openCity(event, 'Buy')"> Find a Home</button>
  <button id= "defaultOpen" class="tablinks" onclick="openCity(event, 'Sell')"> Sell Your Home</button>
</div>

<div id="Buy" class="tabcontent">
  <h2>Let Us Help You Find Your New Home in Our "Island" Paradise</h2>
  <a class="landing-button" href="https://westseattlerealty.idxbroker.com/i/west-seattles-latest-listings">Search West Seattle's Latest Listings</a>
</div>

<div id="Sell" class="tabcontent">
  <h2>Get an Expert Opinion from a Trusted Neighbor & West Seattle's Foremost Real Estate Experts</h2>
  <a class="landing-button" href="https://westseattlerealty.idxbroker.com/i/west-seattles-latest-listings">Request a Personalized Competitive Market Analysis</a>
</div>

1 个答案:

答案 0 :(得分:0)

谢谢布拉玛,你是正确的。将javascript注入标头,并在下面显示HTML代码块。 DOM尚未加载该元素,因此未找到ID为defaultOpen的元素。

我不得不移动一小段javascript: document.getElementById(“ defaultOpen”)。click();

到页脚,它立即起作用。 非常感谢!