只有当另一个元素包含某个属性时,我才试图编写一个脚本来向元素添加一个class属性。这是HTML源代码:
<fieldset class="step1 option0">
<legend><b>Options</b></legend>
<p>
<input id="question_1" name="group_1" type="radio" MadCap:conditions="guideConditions.ProductA" />
<label for="question_1" MadCap:conditions="guideConditions.ProductA">Option 1</label>
</p>
<p>
<input id="question_2" name="group_1" type="radio" />
<label for="question_2">Option 2</label>
</p>
</fieldset>
<fieldset id="question_1_1" class="hide step2 option1" MadCap:conditions="guideConditions.ProductA">
<legend><b>Outcome:</b>
</legend>
<p>This should be only displayed for product A</p>
</fieldset>
<fieldset id="question_1_2" class="hide step2">
<legend><b>Outcome:</b>
</legend>
<p>I want to add an "option1" class if the element with id="question_1" contains the property "MadCap:conditions". If the property is not present, "option2" should be added</p>
</fieldset>如果id "option1“的输入元素包含”MadCap:question_1“属性,我希望脚本将一个"question_1_2”类添加到id“question_1_2”字段集中。否则,脚本应该添加一个"option2“类(字段集class=”隐藏step2 option1“id="question_1_2”与字段集class=“隐藏step2 option2”id="question_1_2")。
这是我尝试过的,但似乎行不通:
<script type="text/javascript">
/*<![CDATA[/>
var element = document.getElementById("question_1"),
var element2 = document.getElementById("question_1_2"),
if (element.hasAttribute('MadCap:conditions')) { // "generate the class dynamically"
element2.classList.add("option1")
} else { // "increment it by one"
element2.classList.add("option2")
}
/]]>*/
</script>有什么办法解决这个问题吗?谢谢!
发布于 2020-08-14 08:39:11
脚本元素以错误的方式使用CDATA:
<script type="text/javascript">
/*<![CDATA[/>
var element = document.getElementById("question_1"),
var element2 = document.getElementById("question_1_2"),
if (element.hasAttribute('MadCap:conditions')) { // "generate the class dynamically"
element2.classList.add("option1")
} else { // "increment it by one"
element2.classList.add("option2")
}
/]]>*/
</script>甚至这个站点上的语法突出显示已经暗示出了一些问题。/* */包围了所有的代码,所以它不会被解析为代码。
现在很少有理由应用这种CDATA模式。见When is a CDATA section necessary within a script tag?。
另外,您应该使用分号来分隔语句,而不是逗号。
如果您确实需要CDATA,那么只将CDATA部件放在JavaScript注释中。例如,像这样:
<script type="text/javascript">
// <![CDATA[/>
var element = document.getElementById("question_1");
var element2 = document.getElementById("question_1_2");
if (element.hasAttribute('MadCap:conditions')) { // "generate the class dynamically"
element2.classList.add("option1");
} else { // "increment it by one"
element2.classList.add("option2");
}
// ]]>
</script>发布于 2020-08-14 07:56:07
用逗号表示Uncaught SyntaxError: Unexpected token 'var',所以如果使用分号,它似乎会起作用:
var element = document.getElementById("question_1");
var element2 = document.getElementById("question_1_2");
if (element.hasAttribute('MadCap:conditions')) {
element2.classList.add("option1")}
else {
element2.classList.add("option2")}https://stackoverflow.com/questions/63408270
复制相似问题