【问题标题】:Javascript Squarespace click() function not workingJavascript Squarespace click()函数不起作用
【发布时间】:2019-03-31 16:48:19
【问题描述】:

以下代码不适用于 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>

【问题讨论】:

  • 您是否在 JavaScript 控制台中遇到任何错误?
  • 你应该在加载html页面后调用你的脚本,尝试在html正文的末尾调用脚本
  • 很可能是这个问题:stackoverflow.com/questions/14028959/…
  • 所以看起来是因为该元素尚未加载到 DOM 中。我正在尝试添加 Jquery 来这样做,但是我仍然没有添加它。我试图把它放在这样的地方:

标签: javascript squarespace


【解决方案1】:

谢谢布拉马尔,你是对的。 javascript 被注入到标头中,HTML 代码块在下面。 DOM 尚未加载该元素,因此它没有找到 ID 为 defaultOpen 的元素。

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

到页脚,它立即工作。 太感谢了!

【讨论】:

    猜你喜欢
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 2015-02-18
    • 2021-03-01
    • 1970-01-01
    • 2022-01-07
    • 2012-08-26
    • 1970-01-01
    相关资源
    最近更新 更多