Jquery:仅更新具有特定类的下一个跨度

Kle*_* S. 5 jquery

HTML:

<p class="fields">
  <select id="parts">
    <option value="10">Ring</option>
    <option value="50">Necklace</option>
    <option value="3">Pendant</option>
  </select>
  <label for="price">Price</label>
  <span class="price"></span>
</p>


function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
    $.ajax({
      url: '/parts/' + value + '/price',
      type: 'get',
              context: this,
      dataType: 'script',
      success: function(responseData) {
        $(this).next("span.price").html(responseData);
      }
    }); 
});
};
Run Code Online (Sandbox Code Playgroud)

我试过这种方式却没有成功.

"onchange"工作正常我只需要一些帮助就可以将span标记内的值显示为内容.

有帮助吗?

ira*_*ama 6

@samccone是在正确的轨道上,但它不适合你,因为span.price不是select#parts元素之后的下一个元素(我假设它是你要发送到load_part_price_select函数的元素).

虽然它是兄弟姐妹之一,所以试试这个:

$(this).siblings("span.price:first").html(responseData);
Run Code Online (Sandbox Code Playgroud)

或者尝试nextAll:

$(this).nextAll("span.price:first").html(responseData);
Run Code Online (Sandbox Code Playgroud)

我将假设'兄弟姐妹'更有效率,因为它不关心匹配元素是在'this'元素之前还是之后.但是如果你不想匹配以前的跨度,请使用'nextAll'.

然后根据samccone的评论设置ajax上下文:

function load_part_price_select(id, value) {
$('#' + id ).live('change',function() {
    $.ajax({
      url: '/parts/' + value + '/price',
      type: 'get',
      context: this,
      dataType: 'script',
      success: function(responseData) {
        $(this).nextAll("span.price:first").html(responseData);
      }
    }); 
});
};
Run Code Online (Sandbox Code Playgroud)