You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用三元运算符实现基于window.OneTrust的script标签属性动态切换

实现方案

完全可以通过三元运算符动态判断属性,消除重复代码,不同开发场景的写法如下:

JSX/React类框架场景

通过扩展运算符动态挂载对应属性,还可以提前抽离公共URL减少重复:

// 提前抽离公共脚本地址
const MAP_SCRIPT_URL = "https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly";

<script
  type={window.OneTrust ? 'text/plain' : 'text/javascript'}
  id="google-maps-api-script"
  className="optanon-category-C0004"
  {...(window.OneTrust ? {'data-src': MAP_SCRIPT_URL} : {src: MAP_SCRIPT_URL})}
></script>

原生JavaScript动态生成场景

直接操作DOM属性,逻辑更清晰:

const MAP_SCRIPT_URL = "https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly";
const script = document.createElement('script');

script.id = 'google-maps-api-script';
script.className = 'optanon-category-C0004';
script.type = window.OneTrust ? 'text/plain' : 'text/javascript';
window.OneTrust ? script.dataset.src = MAP_SCRIPT_URL : script.src = MAP_SCRIPT_URL;

document.body.appendChild(script);

原生HTML模板场景

用模板字符串拼接输出标签:

<script>
const MAP_SCRIPT_URL = "https://maps.googleapis.com/maps/api/js?key=<?php echo get_field('google_maps_api_key', 'option') ?>&v=weekly";
document.write(`
<script
  type="${window.OneTrust ? 'text/plain' : 'text/javascript'}"
  id="google-maps-api-script"
  className="optanon-category-C0004"
  ${window.OneTrust ? `data-src="${MAP_SCRIPT_URL}"` : `src="${MAP_SCRIPT_URL}"`}
><\/script>
`);
</script>

内容的提问来源于stack exchange,提问作者user16645285

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 02:36:08