错误未捕获错误:语法错误,无法识别的表达式

时间:2016-11-01 06:56:51

标签: javascript jquery

<div class="mt-repeater-item">
    <div class="row mt-repeater-row">
        <input type="text" name="product[0][price]" value="2" oninput="update_total(this)">
    </div>
</div>
<div class="mt-repeater-item">
    <div class="row mt-repeater-row">    
        <input type="text" name="product[1][price]" value="3" oninput="update_total(this)">
    </div>
</div>

我的剧本

function update_total(input) {
    var sum = 0;
    $('.mt-repeater-item').each(function(index) {
        var product_price = $("input[name=product["+index+"][price]]").val() ? $("input[name=product["+index+"][price]]").val() : 0;
        sum = sum + product_price;
    });
    alert(sum);
}

Error Uncaught Error: Syntax error, unrecognized expression =&gt;如何解决?

2 个答案:

答案 0 :(得分:1)

function update_total(input) {
    var sum = 0;
    $('.mt-repeater-item').each(function(index) {
            var product_price = $("input[name='product["+index+"][price]']").val() ? $("input[name='product["+index+"][price]']").val() : 0;
        sum = sum + parseInt(product_price);
    });
    alert(sum);
}

name的值括在单引号

答案 1 :(得分:1)

您缺少名称引用 -

function update_total(input) {
    var sum = 0;
    $('.mt-repeater-item').each(function(index) {
        var product_price = $("input[name='product["+index+"][price]']").val() ? $("input[name='product["+index+"][price]']").val() : 0;
        sum = sum + product_price;
    });
    alert(sum);
}

链接 - https://jsfiddle.net/80op2y19/