建筑jquery复选框 - 不能设置选中的值 [英] building jquery checkbox - can't set checked value

查看:201
本文介绍了建筑jquery复选框 - 不能设置选中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这看起来很简单,我不知道这是一个错误,还是我做错了。

this seems straightforward enough, I don't know if it's a bug, or just something I'm doing wrong.

我想做的是构建一个checkbox输入在jquery中,然后返回输入的字符串。我有这个代码:

What I want to do is build a checkbox input in jquery, then return the string of the input. I have this code:

var obj = $('<input>');
obj.attr('disabled', 'disabled');
obj.attr('type', 'checkbox');
obj.attr('checked', 'checked'); // this does not work!

无论我如何尝试渲染这个obj,'checked'

no matter how i try to render this obj, the 'checked' attribute never gets outputted.

所以我试过:

$('<div>').append(obj).remove().html();

并返回:

<input type="checkbox" disabled="disabled" />

我已经尝试设置id属性,它没有什么区别。我也尝试过,但它不工作:

I have tried setting an id attribute, it makes no difference. I have also tried this but it doesn't work:

obj.attr('checked', true);

有关如何获取输入标签的建议,将checked属性设置为checked jquery)?

Any suggestions on how to get the input tag rendered with the checked attribute set to 'checked' (via jquery)?

我意识到我可以使用字符串连接,但现在我真的想知道为什么它不工作的方式应该。

I realise I can just do this with string concatenation, but now I really want to know why it's not working the way it should.

EDIT

您可以在firebug中自己试试。以我的方式或 cletus 方式创建obj,然后尝试将其呈现为字符串。你会发现'checked'属性从不被渲染。

You can try this for yourself in firebug. Create the obj either my way or cletus' way, then try to render it to a string. You'll find that the 'checked' attribute never gets rendered.

推荐答案

你是正确的有一些奇怪的 属性。它似乎只有在它实际上由浏览器呈现之后才会生效。

You are correct there is some weirdness with the "checked" attribute. It seems that it takes effect only after it is actually rendered by the browser. (And not while just in a fragment.)

例如,使用您的代码,

var obj = $('<input />');
obj.attr('disabled', 'disabled');
obj.attr('type', 'checkbox');
obj.attr('checked', 'checked');
var wrapper = $('<div />').append(obj);
alert(wrapper.html());       // notice, no checked attr in this string...
$('body').prepend(obj);      // but now notice, it IS checked when it's drawn!

我知道这不是一个真正的答案,但是想让你知道你不要紧。我很好奇也知道为什么会这样。

I know this isn't really an "answer" per se, but wanted to let you know you're not going nuts. I'd be curious also to know why this is the case.

最好的运气!

这篇关于建筑jquery复选框 - 不能设置选中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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