javascript - this.prop 不是一个函数?

标签 javascript jquery

我的 jQuery 代码是:

$('#edit').click(function(){
    var data = $("#list :input").serialize();
    $.post($("#list").attr('action'), data, function(json) 
    {
        currentRow = json.rowArr[0];
        $("#id").val(currentRow.id);
        $("#id_disp").val(currentRow.id);
        $("#shop").val(currentRow.shop);
        $("#category").val(currentRow.category);
        $("#item").val(currentRow.item);
        $("#qnty").val(currentRow.qnty);
        $("#unit").val(currentRow.unit);

        $.each($("#price_based_on").children('option'), function(index, val) {
            if(this.value.toUpperCase()==currentRow.price_based_on.toUpperCase())
            {
                console.log("Match");
                this.prop("selected", true);
            }
        });

        $("#mrp").val(currentRow.mrp);
        $("#sellers_price").val(currentRow.sellers_price);
        $("#last_updated_on").val(currentRow.last_updated_on);

    },"json");
});

其中,唯一感兴趣的是以下几行:

$.each($("#price_based_on").children('option'), function(index, val) {
    if(this.value.toUpperCase()==currentRow.price_based_on.toUpperCase())
    {
        console.log("Match");
        this.prop("selected", true);
    }
});

使用语句 this.prop("selected", true); 我收到错误:

Uncaught TypeError: this.prop is not a function

当 .prop() 显然是一个存在的函数时,为什么会发生这种情况?我该如何修复它?

最佳答案

$.each 用于迭代对象或数组。如果您想迭代 jQuery 对象中的节点,请使用 .each,如下所示:

$("#price_based_on").children('option').each(function() {
     ... code here
});

在回调中,this 引用 native DOM 元素(它没有 prop 方法,因此您可能想要执行类似的操作来获取对保存 DOM 节点的 jQuery 对象的引用:

$("#price_based_on").children('option').each(function() {
    var $this = $(this);
    $this.prop('selected',true)
});

关于javascript - this.prop 不是一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41211560/

相关文章:

Javascript 将数字添加为字符串

javascript - 根据表单字段值修改 CSS (Pardot)

javascript - Jquery 带条件选择选项

javascript - 如何在 JavaScript 中解析这个 JSON 对象?

jQuery 多个 if else 语句卡在第二个条件

javascript - 如何让 JavaScript 继续使用 ResonseText 数据

javascript - 如何用jsp变量传递onclick并直接到其他页面

javascript - 如何使用 Vue 构建动态 CSS 网格?

jquery - 没有 jquery UI 的可拖动 div 不能很好地拖动

javascript - 删除确认对话框仅适用于表中的第一行