【问题标题】:JQuery functions with $ not running in head tag of HTML带有 $ 的 JQuery 函数未在 HTML 的 head 标记中运行
【发布时间】:2022-10-07 00:36:27
【问题描述】:

由于 Squarespace 的限制,我只能通过 Head 标签添加代码。每当脚本到达 JQuery 的 $ 部分时,它似乎根本不会运行它。我已经用大量的console.log()s 进行了测试,我注意到网页只是跳过了$(document)$(\".appoinment-type-name\")

这是我在<HEAD> 标签中注入的代码。当我将它粘贴到 Chrome 的开发人员工具的控制台中时,这很有效。

<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js\"></script>

<script type=\"text/javascript\">
const token = \"xxxxxxxxxxx\";
var url = \"https://ipinfo.io/json?token=\" + token;
var userCountry = \"\";
var str =\"\";
var re = new RegExp(\'^IVA\');


if (navigator.userAgent.match(/bot|spider/i)) {
    //Request is a bot, do nothing
} else {
    fetch(url)
        .then(res => res.json())
        .then(data => runScript(data.country))
}

function runCountryCheck(country) {
        userCountry = country;
        console.log(\'User is in: \' + userCountry);
        return(country);
}
function removeRegex() {
    $(document).ready(function(){
        $(\".appointment-type-name\").each(function() {
        if (userCountry == \"US\") {
            str = $(this).html();
            if (str.match(re)) {
                // do nothing
            } else {
                $(this).closest(\'.select-item-box\').css(\'display\', \'none\');
            }
        } else {
            str = $(this).html();
            if (str.match(re)) {
                $(this).closest(\'.select-item-box\').css(\'display\', \'none\');
            }
        }
     }); 
    });
}

function runScript(country) {
    runCountryCheck(country);
    removeRegex();
}
</script>

  • 你关注these instructions了吗?看起来您需要将 jQuery 添加到设置的“代码注入”部分。
  • 如果您查看 html - 在您尝试使用 $?
  • @angel.bonev jQuery 运行 .ready 即使在页面加载后附加。

标签: javascript html jquery squarespace


【解决方案1】:

您在函数中使用$(document).ready(function(),但它是在您的页面加载时运行的事件(很简单)。

当您调用该函数时,您会创建事件,但不会在其中运行脚本。 只需在功能上删除它并在“if ... else”上添加就绪事件。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script type="text/javascript">
    const token = "xxxxxxxxxxx";
    var url = "https://ipinfo.io/json?token=" + token;
    var userCountry = "";
    var str ="";
    var re = new RegExp('^IVA');

    $(document).ready(function(){
        if (navigator.userAgent.match(/bot|spider/i)) {
            //Request is a bot, do nothing
        } else {
            fetch(url)
            .then(res => res.json())
            .then(data => runScript(data.country))
        }
    });
</script>

【讨论】:

    最近更新 更多