jQuery select id使用字符串但不使用变量

时间:2017-11-08 17:26:59

标签: javascript jquery string select

我想创建一个脚本,读取每行的供应商名称,并选择包含相同字符串的选项。

我无法弄清楚为什么我的jQuery脚本的最后两行表现不同。

最后一行正在运行(选择带有[Supplier2]名称的正确选项),但前提是我将id作为字符串。

即使我将id作为变量赋予相同的字符串,注释掉的行也不起作用。任何想法为什么会这样?

JSFiddle

$('#cart_table > tbody  > tr').each(function(i) {
    var actual_supplier = "[" + $(this).find(".actual_supplier").text() + "]";
    var item_id = $('select').attr('id');
    alert(item_id); // printed item_id looks like the same as id=supplier-selection-254
    console.log(i, actual_supplier, "id=",item_id);

// ------------------------- This is not working:

    //$('select[id=item_id] option:contains("[Supplier2]")').prop('selected',true); // This line should do the job but somehow not working with the same id name

// ------------------------- This is working:

    $('select[id=supplier-selection-254] option:contains("[Supplier2]")').prop('selected',true); // This line looks the same as line above it above

});
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>  
<table id="cart_table" class="table table-striped">
  <thead>
          <tr>
            <th>Supplier</th>
            <th>Item</th>
          </tr>
  </thead>
  <tbody>
          <td class="actual_supplier hidden">[Supplier2]</td>  
          <td><div>      
            <form id='change-supplier-form' method='GET' action=".">
              <select id=supplier-selection-254 name='item' class='form-control supplier_select'>
              <option  value = "Car1">Car 1 - [Supplier1]</option>
              <option  value = "Car2">Car 2 - [Supplier2]</option>
              <option  value = "Car3">Car 3 - [Supplier3]</option>
              </select>
            </form>
          </div></td>
  </tbody>

1 个答案:

答案 0 :(得分:2)

你错过了引号。

 $( "select[id='" + item_id + "']" );