3

With Jquery, I'm looping through the attribute named tags, in each <option> of the <select> dropdown below.

You'll see I would LOVE to have 2 of the options preselected, if the number 6 exists in the tags attribute.

<select name="someFun" id="someFun"  multiple="multiple">
  <option value="1" tags="4,6,7">something</option>
  <option value="44" tags="2">something</option>
  <option value="61" tags="1,3,6">something</option>
  <option value="44" tags="2">something</option>
</select>

<script language="javascript" type="text/javascript">
$(document).ready(function(){

  var preselectedtag = '6'; // auto select any with 6

  $("#someFun > option").each(function() {
     var tag = $(this).attr("tags");

     /* change attr of this option to "selected" if 6 exists in var tag */

  });

});
</script>

I could use some help here. Is there a best way to do this?
In PHP I normally use an in_array() function, but javascript seems way more picky.

4

2 回答 2

4

jQuery有一个inArray()功能:

var tags = $(this).attr("tags").split(",");
if ($.inArray(preselectedtag, tags) > -1) {
  alert("Tag " + preselectedtag + " detected!");
}

编辑

选择检测到的选项标签的 OP 代码的重构版本:

$(function(){
  var preselectedtag = '6',
      selected = [];
  $("#someFun > option").each(function() {
    var n = $(this), 
        tags = n.attr("tags").split(",");
    if ($.inArray(preselectedtag, tags) > -1) {
      selected.push(n.val());
    }
  });
  $('#someFun').val(selected);
});

http://jsfiddle.net/zFBVT/

于 2013-01-30T22:39:41.163 回答
1

拆分它,并检查呢?

var tags = tag.split(",")
if(tags.indexOf("6")!==-1){
    //do whatever manipulation you desire
}
于 2013-01-30T22:39:00.423 回答