如何使用 JavaScript 变量设置属性

how to set attribute using javascript variable

本文关键字:设置 属性 变量 JavaScript 何使用      更新时间:2023-09-26

以下是我在杜兰达尔应用程序中的 cshtml 代码

<script type="text/javascript" src="~/Scripts/require.js" 
  id="countryscript" data-main="**here i have to set value**"></script>

我想用我的 javascript 变量值设置脚本属性 data-main。如何实现这一点?

我试过了

document.getElementById("countryscript").data-main = countrycode;

它在 = 符号附近显示语法错误。需要帮助..

试试这个:

document.getElementById("countryscript").setAttribute("data-main", countrycode);

自MDN

var d = document.getElementById("countryscript"); 
d.setAttribute("data-main", countrycod);

或者如果你有JQuery,这要容易得多

$('#countryscript').attr("data-main", countrycod);