我會提出一個建議,而不是爲每個輸入查看不同的元素,將標題文本存儲爲input
本身的屬性。 title
屬性是完美的。
考慮到這一點,下面的代碼片段應該工作:
HTML:
爲清楚起見稍微簡化。我已經爲表單,輸入和摘要元素添加了類。
<form class="order-form">
<table>
<tr>
<td><input type="number" class="quantity" title="Product 1"/></td>
</tr>
<tr>
<td><input type="number" class="quantity" title="Product 2"/></td>
</tr>
<tr>
<td><input type="number" class="quantity" title="Product 3"/></td>
</tr>
</table>
<div class="order-form-summary"></div>
</form>
的Javascript:
$(function(){
// Find all of the DOM elements we're interested in:
var form = $('form.order-form'),
output = form.find('.order-form-summary'),
inputs = form.find('input.quantity');
// Bind a custom event handler to the form, that collects the titles from the
// inputs with a value > 0
form.bind('updateSummary', function(){
// Collect the titles into an array
var summaries = $.map(inputs, function(e){
var input = $(e);
if (parseInt(input.val()) > 0){
return input.attr('title');
}
});
// Update the output element's HTML with the array, joined to a string with commas.
output.html(summaries.join(', '));
});
// Fire the update event whenever chance, key-up or blur occurs on any input
inputs.on('change keyup blur', function(){form.trigger('updateSummary')});
// Fire it on load to get the correct starting values (in case any inputs are already filled)
form.trigger('updateSummary');
});
這個代碼可以凝結,但我的目的是把它的可讀性。這裏有一個小例子:https://jsfiddle.net/ejwLy5x8/
你在哪裏計算數量*價格? – asifrc
我有一個JavaScript函數,可以計算數量*價格和類runningtl的地方。但是,如果數量大於0,我不知道如何顯示h6標記內容。 – Palemo
您可以發佈計算代碼還是鏈接[jsfiddle](http://jsfiddle.net)? – asifrc