The “checked” attribute of checkbox does not get enabled if the html is created dynamically

安稳与你 提交于 2019-12-21 18:32:19

问题


I have created a listview containing checkbox. On few of the list items I wanted the checkbox to be checked. The listview is created dynamically as the content comes from the server.

I have the following jsfiddle code. http://jsfiddle.net/praleedsuvarna/rN28z/

Can you please help me solve this problem? Thanks in advance

below is an example of my dynamic list content where the 2nd and 3rd checkbox is set to "checked"

$(document).on('pageshow', '#index', function(){     
    var list = '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox"/>'+
    '   </div>  '+
    '   <a href="item1.html" class="detailListText">item1</a>'+
    '</li>'+
    '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox" checked="checked"/>'+
    '   </div>'+
    '   <a href="item1.html" class="detailListText">item2</a>'+
    '</li>'+
    '<li>'+
    '   <div class="checkBoxLeft">'+
    '       <input type="checkbox" name="checkbox-0" id="checkbox-0" class="hidden-checkbox" checked="checked"/>'+
    '   </div>                     '+
    '   <a href="item1.html" class="detailListText">item3</a>'+
    '</li>'

    $("#viewdata").html(list);
    $("#viewdata").listview("refresh");
});

below is my html page

<body>
    <div data-role="page" id="index">
        <div data-theme="a" data-role="header">
            <h3>
                First Page
            </h3>
            <a href="#second" class="ui-btn-right">Next</a>
        </div>

        <div data-role="content">
            <ul data-role="listview" data-theme="a" id="viewdata">
            </ul>
        </div>

        <div data-theme="a" data-role="footer" data-position="fixed">

        </div>
    </div>   
</body>

回答1:


Fixed and a little cleaned up version: http://jsfiddle.net/rN28z/6/

I moved this code:

$('input[type="checkbox"]').each(function() {
    $(this).parent('.checkBoxLeft').addClass(this.checked ? 'checked' : 'not-checked');
});

inside pageshow handler. You were calling it on pagebeforeshow and by that time your HTML had not been yet populated.



来源:https://stackoverflow.com/questions/15446907/the-checked-attribute-of-checkbox-does-not-get-enabled-if-the-html-is-created

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