jquery on show和on hide不使用类选择器

时间:2012-08-06 04:57:37

标签: jquery-selectors jquery

我正在尝试在文本区域中输入某些角色,并使用bootstrap在弹出框中突出显示。

预期的行为是必须突出显示所选角色,当我将id选择器用于jquery时代码有效,但相同的代码不适用于类选择器

<textarea name="options" id="options" cols="30" rows="10">admin user</textarea>


<a class="btn" data-toggle="modal" href="#myModal">Launch Modal</a>
<div class="modal hide fade" id="myModal" class="myModal">
    <div class="modal-header">
        <a class="close" data-dismiss="modal">×</a>
        <h3>Modal header</h3>
    </div>
    <div class="modal-body">
        <div>
            <ul>
                <li class="mlist">admin</li>
                <li class="mlist">user</li>
                <li class="mlist">guest</li>
                <li class="mlist">blank</li>
            </ul>
        </div>
    </div>
    <div class="modal-footer">
        <a href="#" class="btn btn-primary" data-dismiss="modal">Close</a>
    </div>
</div>

<script type="text/javascript">

    $(document).ready(function (){
        console.log('Inside onready');
        $('.myModal').on('show', function () {
            console.log('Inside show');
            var option = $('#options').val();
            var options = option.split(" ");
            console.log('Selected roles: ' + options);

            for (var index = 0; index < options.length; index++) {
                highlight(options[index]);
            };
        });
        $('.myModal').on('hide', function () {
            console.log('Inside onhide');
            $('.mlist').removeClass('btn-primary');
        });
    });

    function highlight(parOptions) {
        $('.mlist:contains("' + parOptions +'")').addClass('btn-primary');
    }

</script>

1 个答案:

答案 0 :(得分:4)

我想这与你的div有两个类标签有关。

<div class="modal hide fade" id="myModal" class="myModal">

更改为

<div class="modal hide fade myModal" id="myModal">