在javaScript中使用$(this)而不是ID

时间:2016-05-05 10:22:25

标签: javascript jquery

$(this)选项中选择使用javaScript代替和ID是否有任何解决方案?

 var tot = 5 * ($( "#firstOne option:selected" ).text());

在上面的示例中,我想使用$(this)而不是#firstOne,以便能够将此功能用于多个选项选择。

更新

jsFiddle

$(document).ready(function() {

  document.getElementById("totalPrice").innerHTML = 0 + " €";
});

function addToPrice() {
  var tot = $("#totalPrice").val();
  tot = 5 * ($(this).find("option:selected").text());
  tot = tot + " €"
  document.getElementById("totalPrice").innerHTML = tot;

}
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>

<div>

  <table class="itemList">
    <tr>
      <td style="width: 170px">
        <span>Arancina Pistacchio</span>
      </td>
      <td>
        <span style="margin-left: 110px;">2.5 &euro;</span>
      </td>
      <td>
        <select style="margin-left: 30px" onChange="addToPrice();">
          <option value="one">0</option>
          <option value="two">1</option>
          <option value="three">2</option>
          <option value="four">3</option>
        </select>
      </td>
    </tr>
  </table>

</div>

<div>

  <table class="itemList">
    <tr>
      <td style="width: 170px">
        <span>Arancina Melanzana</span>
      </td>
      <td>
        <span style="margin-left: 110px;">2.5 &euro;</span>
      </td>
      <td>
        <select style="margin-left: 30px">
          <option value="one">0</option>
          <option value="two">1</option>
          <option value="three">2</option>
          <option value="four">3</option>
        </select>
      </td>
    </tr>
  </table>

</div>

<div class="totPrice">Total :</div>
<div class="totPrice" style="font-size: 20px; font-family: Helvetica" id="totalPrice"></div>

3 个答案:

答案 0 :(得分:3)

如果你的意思我得到了。使用如下:

var tot = 5 ;
$( "option:selected" ).each(function(){
tot = tot * $(this).text();
});

答案 1 :(得分:1)

  

是否有任何解决方案可以使用$(this)代替和选项中的ID   在javaScript中选择?

是的,试试

var tot = 5 * ( $(this).find("option:selected" ).text());

你需要在你的小提琴中做多件事

  1. 选择No Wrap - In Head选项

  2. 选择jQuery版本

  3. 将当前对象this作为参数传递给函数。

答案 2 :(得分:1)

你可以使用

$( "option:selected",this ).text()

DEMO