Jquery链不工作在我的HTML与每个函数

jquery chaining not working in my html with each function

本文关键字:函数 HTML 我的 工作 Jquery      更新时间:2023-09-26

这是我的html

<div  class="productcheck">
    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>
</div>
<div  class="productcheck">
    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>
</div>
<div  class="productcheck">
    <div class="expenserow1">
        <select name="product[]" class='product_name'>
            <option value="A">A</option>
            <option value="B">B</option>
            <option value="C">C</option>
        </select>
    </div>
    <div class="expenserow2">
        <input type="text" name="productpercent[]" size=3 maxlength=3 value="100">
    </div>
</div>

JS:

<script>
$(document).ready(function(){
  $(".productcheck .expenserow2 input[type='text']").each(function() {
            var product_percentage=$(this).val();
            var product_name=$(this).closest('.product_name:selected').val();
            console.log(product_percentage);
  });
});
</script>

我得到product_percentage值正确,但不能得到product_name值

您需要使用正确的选择器来选择元素。用途:

$(this).parent().prev().find('.product_name').val();
演示工作

问题是你的选择器。product_name不是文本框的父元素,所以你的代码不能工作。

使用

var product_name = $(this)
    .closest('.productcheck') //traverse to parent productcheck
    .find('.product_name').val(); //Use .find() to search product_name You don't need selected here