jQuery"选择“:与'选择'选项标记中的属性

jQuery "chosen": conflict with 'selected' attribute in option tag

本文关键字:选择 属性 quot jQuery 选项      更新时间:2023-09-26

由于与jQuery插件"selected"发生"冲突",我的jQuery代码段无法正常工作。我正在使用Wordpress,以备不时之需。

我想使用在几个<option>标签中设置selected属性

jQuery( document ).ready(function() {
var arr = ["1", "2"];
jQuery("#location option").each(function () {
    if (jQuery.inArray(jQuery(this).val(), arr) != -1) {
        jQuery(this).prop('selected', true);
    };
});
});

html输出

 <select name="location[]" multiple="multiple" id="location" class="postform" style="display: none;">
        <option value="-1">Select a location</option>
        <option class="level-0" value="1">Location A</option>
        <option class="level-0" value="2">Location B</option>
        <option class="level-0" value="3">Location C</option>
    </select>

我觉得我在这里提供了一些小细节来解决这个问题,但我不确定在这里发布什么额外的代码。

禁用(而不是排队)chosen插件(chosen.jquery.min.js)时,一切正常。尽管如此,我还是希望chosen插件能够正常工作。

您的代码确实可以工作,尽管这是您调用它的顺序-这可能会有点磕磕碰碰。如Fiddle中所示。

functions.php

<?php 
    /**
     *  Load:
     *    css; chosen; jquery.
    **/
    function wordpress_scripts() {
        wp_enqueue_style( 
                   'chosen.css', 
                   get_stylesheet_uri() 
                 );
        wp_enqueue_script( 
                   'chosen.js', 
                   get_template_directory_uri() . '/js/chosen.js', 
                   array('jquery')
                 );
        wp_enqueue_script( 
                   'myscript.js', 
                   get_template_directory_uri() . '/js/myscript.js', 
                   array('jquery')
                 );
    }
    add_action( 'wp_enqueue_scripts', 'wordpress_scripts' );
?>

myscript.js

<script>
    jQuery(document).ready(function(){
         var arr = ["1", "2"];
         jQuery("#location option").each(function () {
             if (jQuery.inArray(jQuery(this).val(), arr) != -1) {
                 jQuery(this).prop('selected', true);
             };
         });
         if ( typeof jQuery.fn.chosen !== 'undefined' )
             jQuery("#location").chosen();
    });
</script>