如何更改子元素的文本?

时间:2018-01-15 08:58:12

标签: jquery select onchange custom-data-attribute

我想更改由数据属性选择的子元素的文本:



$('.service').change(function () {
     var dataid = $(this).data('id');
     var status = $(this).val();
     console.log(dataid);
     $(".productdetails[data-product_id='" + dataid + "']").find(".status_result").text(status);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr class="productdetails" data-product_id="91"><td class="status_result"><span class="label label-primary">in process </span></td>
</tr>


<select class="service" data-id="91">
      <option selected="">in process</option>
      <option>done</option>
</select>
&#13;
&#13;
&#13;

但是文字没有改变......

3 个答案:

答案 0 :(得分:3)

您的HTML无效,您<tr>以外的<td><table>无效。当您修复HTML时,代码可以正常工作。

&#13;
&#13;
$('.service').change(function() {
  var dataid = $(this).data('id');
  var status = $(this).val();
  console.log(dataid);
  $(".productdetails[data-product_id='" + dataid + "']").find(".status_result").text(status);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="productdetails" data-product_id="91">
    <td class="status_result"><span class="label label-primary">in process </span></td>
  </tr>
</table>

<select class="service" data-id="91">
      <option selected="">in process</option>
      <option>done</option>
</select>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

$('.service').change(function() {
  var dataid = $(this).data('id');
  var status = $(this).val();
  $(".productdetails[data-product_id='" + dataid + "']").find(".status_result").text(status);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr class="productdetails" data-product_id="91">
    <td class="status_result"><span class="label label-primary">in process </span></td>
  </tr>
</table>

<select class="service" data-id="91">
      <option selected="">in process</option>
      <option>done</option>
</select>

答案 2 :(得分:0)

如果没有桌子,您就无法使用tr,它会被删除而您无法将其定位。添加表格,它将被修复

&#13;
&#13;
$('.service').change(function () {
     var dataid = $(this).data('id');
     var status = $(this).val();
     console.log(status);
     $(".productdetails[data-product_id=" + dataid + "]").find(".status_result span").text(status);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr class="productdetails" data-product_id="91">
<td class="status_result">
<span class="label label-primary">in process </span></td>
</tr>
</table>

<select class="service" data-id="91">
      <option  selected="">in process</option>
      <option >done</option>
</select>
&#13;
&#13;
&#13;