繁体   English   中英

将 HTML 元素的 class 更改为 Javascript

[英]Change class of an HTML element with Javascript

我需要根据用户使用单选按钮所做的选择即时更改 HTML 元素的 class 元素,但问题是我收到消息

“错误:参数列表 Fichier 之后缺少)来源:网站 Ligne:1,Colonne:71 代码来源:document.getElementById('jj_conjoint').setAttribute('class','validate['required']');”。

我的代码:

<label>Husband/Wife :</label>
    <input type="radio" name="not_single" value="yes" onclick="document.getElementById('birthdate_partner').setAttribute('class','validate['required']');">yes
    <input type="radio" name="not_single" value="no" checked="checked">no


<select name="birthdate_partner" id="birthdate_partner">
   <option value="" selected="selected">-</option>
   <option value="1987" >1987</option>
   <option value="1986" >1986</option>
   <option value="1985" >1985</option>
   <option value="1984" >1984</option>
</select>

您没有引用 ID 字符串,因此document.getElementById返回null因为未引用的字符串被视为未初始化的变量,其计算结果为undefined

document.getElementById('birthdate_partner').setAttribute('class',validate['required']);
document.getElementById(birthdate_partner)

指的是一个名为birthdate_partner的变量。 相反,您应该将 ID 作为字符串传递:

document.getElementById('birthdate_partner')

变量birthdate_partner从未分配给某个值,因此它是undefined ,导致它被调用:

document.getElementById(undefined)

这是行不通的。

您可以使用 jQuery 来执行此操作:

$("[name=birthdate_partner]").removeClass(className);
$("[name=birthdate_partner]").addClass(className);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM