简体   繁体   English

jQuery文档更改:我可以使用变量作为选择器吗?

[英]Jquery document on change: can I use variable as selector?

I am very new to javascript and jQuery. 我对javascript和jQuery非常陌生。 In my view, I have a List of QuoteDetails, as follows: 在我看来,我有一个QuoteDetails列表,如下所示:

<div class="col-md-10" id="QuoteDetails">
    @for (int i = 0; i < Model.QuoteDetail.Count; i++)
    {
        <div id="row">
            @Html.HiddenFor(model => model.QuoteDetail[i].QuoteId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.HiddenFor(model => model.QuoteDetail[i].QuoteDetailId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ProductId, new { htmlAttributes = new { @id = "PId", @class = "form-control", style = "width: 75px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ProductName, new { htmlAttributes = new { @id = "Product", @class = "form-control", style = "width: 300px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control", style = "width: 95px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].ListPrice, new { htmlAttributes = new { @id = "Lprice", @class = "form-control", style = "width: 95px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Discount, new { htmlAttributes = new { @class = "form-control", style = "width: 100px" } })
            @Html.EditorFor(model => model.QuoteDetail[i].Price, new { htmlAttributes = new { @id = "Pr", @class = "form-control", style = "width: 100px" } })
            @Html.ValidationMessageFor(model => model.QuoteDetail, "", new { @class = "text-danger" })
    }

When either the Amount or Discount is changed by the user, I want to recalculate the Price. 当用户更改金额或折扣时,我要重新计算价格。 I am trying to solve it with the following javascript/jQuery: 我正在尝试使用以下javascript / jQuery解决此问题:

<script type="text/javascript">
    $(document).ready(function () {
        var quoteDetails = $('[name*="QuoteDetailId"]');
        var amounts = $('[id*="Amount"]')
        var discounts = $('[id*="Discount"]')
        var prices = $('[id*="Price"]')
        var listPrices = $('[id*="LPrice"]')
          for (var i = 0; i < quoteDetails.length; i++) {
            $(document).on("change", discounts[i], amounts[i], function calculate() {  
                var finalPrice = $(amounts[i]).val() * ($(listPrices[i]).val() * ((100 - $(discount[i]).val()) / 100)) 
                $(prices[i]).val(finalPrice);
            });
        };
    });
</script>

Is there a way to use variables with indices as jQuery selectors in the document.on change? 有没有一种方法可以将带有索引的变量用作document.on更改中的jQuery选择器? Any help will be much appreciated. 任何帮助都感激不尽。

Give your elements class names, eg 给您的元素类名,例如

@Html.EditorFor(m=> m.QuoteDetail[i].Amount, new { htmlAttributes = new { @class = "form-control amount"} })

and change the container to <div class="row"> 并将容器更改为<div class="row">

(ditto for discount , listprice and price ) (同上,用于discountlistpriceprice

Then your script becomes 然后你的脚本变成

$('.amount, .discount').change(function() {
    // Get container
    var row = $(this).closest('.row');
    // Get values
    var amount = Number(row.find('.amount').val());
    var listprice = Number(row.find('.listprice').val());
    var discount = Number(row.find('.discount').val()); 
    // Validate
    if (isNaN(amount) || isNaN(listprice) || isNaN(discount))
    {
        return; // may want to display an error message?
    }
    // Calculate
    var finalPrice = amount * listprice * ((100 - discount) / 100)
    // Update
    row.find('.price').val(finalPrice);
})

A few things to note: 注意事项:

  • Duplicate id attributes are invalid html - remove all your new { @id = ".." code. 重复的id属性无效的html-删除所有new { @id = ".."代码。
  • Because of your class names, you can now style the widths - eg .price { width: 95px; } 由于您的班级名称,您现在可以设置宽度的样式-例如.price { width: 95px; } .price { width: 95px; }
  • Convert the values to a Number and check that the value is valid using isNaN before doing the calculation 将值转换为Number并在执行计算之前使用isNaN检查该值是否有效
  • Since Price is a calculated field, it should not be editable in the view (or have a setter in the model. Use a <div> or similar element to display it (and then use row.find('.price').text(finalPrice); to set it 由于Price是一个计算字段,因此不应在视图中进行编辑(或在模型中包含setter 。请使用<div>或类似元素将其显示(然后使用row.find('.price').text(finalPrice);进行设置

Note also that .on() is not necessary unless your dynamically adding those elements after the view has been first generated. 还要注意,除非您在第一次生成视图后动态添加这些元素,否则不需要.on()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM