如何基于google-maps-api-script脚本的type属性编写if else条件
实现方案
你通过jQuery选择器获取到的是jQuery封装的类数组对象,有两种常见方式实现你的判断逻辑:
方式一:使用jQuery内置attr()方法(最简洁)
直接通过jQuery提供的属性读取方法获取type属性值做判断:
const $script = $('#google-maps-api-script'); const currentType = $script.attr('type'); if (currentType === 'text/plain') { // 执行type为text/plain时的逻辑 } else if (currentType === 'text/javascript') { // 执行type为text/javascript时的逻辑 }
方式二:读取原生DOM节点属性(和你控制台打印的结构对应)
从jQuery对象的0号索引取出原生DOM节点,再读取type属性:
const $script = $('#google-maps-api-script'); // 取索引0的元素即为原生script标签DOM对象 const rawScript = $script[0]; const currentType = rawScript.type; if (currentType === 'text/plain') { // 执行type为text/plain时的逻辑 } else if (currentType === 'text/javascript') { // 执行type为text/javascript时的逻辑 }
可选兼容处理
如果存在页面加载时该script标签还未插入的场景,可以先判断元素是否存在,避免读取属性时报错:
const $script = $('#google-maps-api-script'); // 仅当元素存在时执行后续逻辑 if ($script.length) { const currentType = $script.attr('type'); // 上述判断逻辑 }
内容的提问来源于stack exchange,提问作者user16645285
相关产品推荐
相关产品推荐

