.attr('checked', 'checked') / .attr('checked', 'true') not adding attribute in html

白昼怎懂夜的黑 提交于 2019-12-10 11:58:22

问题


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);

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');

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

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


回答1:


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);
}



回答2:


If you want to copy an element, use .clone(). Working with HTML is messy.

$('#copy').replaceWith(
    $('#E_DIV_H').clone().attr('id', 'copy')
);

Anyways, the reason it isn’t working is probably because (as you know) .prop() was introduced in 1.6.0; before then, .attr() did its job and is probably setting the property instead of the attribute.



来源:https://stackoverflow.com/questions/27679690/attrchecked-checked-attrchecked-true-not-adding-attribute-in-h

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!