首页 > 解决方案 > If else 取决于脚本类型

问题描述

所以我正在研究一个小片段来确定何时注入 HTML,并且我很难正确定位正确的条件。

所以下面,我将详细介绍我正在尝试做的事情:

<script>在页脚中嵌入了以下内容,其 ID 根据插件将“text/plain”更改为“text/javascript”:

<script type="text/plain" id="google-maps-api-script" class="optanon-category-C0004" src="https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly"></script>

在 js 中,我在控制台中使用以下命令记录元素 ID:

const script = $('#google-maps-api-script');
console.log(script);

这给了我一个带有 [0] 索引的 S.fn.init 返回:
在此处输入图像描述

现在在属性内部,我希望能够根据脚本类型执行 If/else 条件。所以属性 -> [0] 或类型 -> nodeValue/value 表明:
在此处输入图像描述

我怎样才能正确地做出一个条件说:

If (#google-maps-api-script type is 'text/plain') {
   // Do something
} else or if it's 'text/javascript')) {
   // Do something else
}

所有帮助将不胜感激!

标签: javascriptjquery

解决方案


用于.attr('type')获取它:

if ($("#google-maps-api-script").attr("type") == "text/plain")) {
    // do something
} else {
    // do something else
}

推荐阅读