我正在尝试使用 jquery 来:
1-动态添加一个复选框 2-正确定位它。
到目前为止,我可以做 1 或 2,但不能做 1 和 2。
这是我的 HTML 代码:
<!-- language: lang-html -->
<body>
<div id='myDiv'></div>
<div id='myOtherDiv'>
<button id='myButton'>my button</button>
</div>
</body>
这是我的js代码:
<!-- language: lang-js -->
jQuery(document).ready(
function ($)
{
jQuery.noConflict();
function createCheckbox()
{
var $myCheckbox = $('<input id="myCheckbox" type="checkbox"></input><label for="myCheckbox">my checkbox</label>');
$('#myDiv').append($myCheckbox);
/*
The following line fixes the "button displayed as unpressed" problem
but it breaks the .position call
*/
// $myCheckbox = $('#myDiv > input');
/* myCheckbox */
$myCheckbox.button({
text: false,
icons: { primary: "ui-icon-refresh"}
});
$myCheckbox.change(
function()
{
if($myCheckbox.is(":checked"))
{ alert('checked'); }
else
{ alert('unchecked');}
}
);
var $myButton = $('#myButton');
$myCheckbox.position({my:"left", at:"right", of:$myButton });
}
createCheckbox();
});
上面的代码有效,但是在单击复选框并单击“已选中”警报上的“确定”后,即使实际复选框已选中,jquery 复选框按钮仍显示为未选中。
通过反复试验,我通过在追加后重新选择我的复选框来解决该问题。我不确定为什么会这样。
$myCheckbox = $('#myDiv > input');
当我取消注释上面的行时,复选框会正常运行并在选中时显示为选中状态。但是随后对 .position 的调用无法正确定位复选框按钮。
见:http: //jsfiddle.net/roumbaba/uM3sS/1/
注意:仅当我动态添加输入/复选框时才会出现此问题。如果我只添加一个简单的按钮(使用普通按钮而不是位置和检查显示状态都可以正常工作。
在整个过程的运作方式中,我显然遗漏了一些重要的东西。特别是我不明白为什么用该行重新选择我的复选框
$myCheckbox = $('#myDiv > input');
更改检查状态按钮的行为。为什么我这样做后位置不起作用。