.attr(' checked')/.attr(' checked',' true' )不在html中添加属性 [英] .attr('checked', 'checked') / .attr('checked', 'true') not adding attribute in html

查看:118
本文介绍了.attr(' checked')/.attr(' checked',' true' )不在html中添加属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的JavaScript,使用jQuery:

This is my JavaScript, using jQuery:

$("#E_DIV_H input[value='E,F']").attr('checked', 'checked');
var data = $('#E_DIV_H').html();
$('#copy').html(data);

将数据从一个<div>(#E_DIV_H)复制到另一个DIV(#copy)时,它将取消选中该复选框,由于以下代码,该复选框已经被选中!

When it copies the data from one <div> (#E_DIV_H) to another DIV (#copy), it unchecks the check box, which should already be checked due to the following code!

$("#E_DIV_H input[value='E,F']").attr('checked', 'checked');

使用Firebug,我看到.attr('checked', 'checked')正在检查复选框而不添加属性.

Using Firebug, I see that .attr('checked', 'checked') is checking the check box without adding the attribute.

有没有可以跨浏览器使用的解决方案?我正在使用jQuery 1.4.2.

Is there any solution that works cross-browser? I’m using jQuery 1.4.2.

推荐答案

要在jQuery版本< 1.6中将布尔属性更新为checked,应使用javascript setAttribute()方法,例如:

To update boolean attribute as checked in jQuery version <1.6, you should use javascript setAttribute() method, e.g:

$("#E_DIV_H input[value='E,F']")[0].setAttribute('checked', true);

如果要指定多个元素,则必须遍历集合,例如:

If you have more than one element to target, then you have to iterate through collection, e.g:

var els = document.querySelectorAll("#E_DIV_H input[value='E,F']");
for (var i=0; i < els.length; i++) {
    els[i].setAttribute("checked", true);
}

这篇关于.attr(&amp;#39; checked&amp;#39;)/.attr(&amp;#39; checked&amp;#39;,&amp;#39; true&amp;#39; )不在html中添加属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆