簡體   English   中英

Noob jQuery“ $”函數返回問題

[英]Noob jQuery “$” function return question

HTML:

<input type="text" id="priceperperson1" name="priceperperson1" />
<input type="text" name="personsvalue1" class="countme" readonly="readonly" />

JS:

jQuery(document).ready(function($) {
$('div.pricerow input.countme').each(function(){ 
var id = this.name.substr(this.name.length-1);
alert($('input#priceperperson'+id));
this.value = parseInt($('priceperperson'+id).value) * parseInt($('countpersons'+id).value); 
});
});

盡可能縮短。 我要提醒的是“對象” ...值是NaN。 我試圖在id上“ parseInt”。 我試過了:

$('[name=priceperperson'+id+']');
$('priceperperson'+id);

我做錯了什么?

在執行$(..)時,您正在檢索jQuery對象$(..)

要獲取值( 字符串 ),請使用.val()方法。

所以

alert( $('input#priceperperson'+id).val() );

您可能應該將$放入函數定義中。

我猜這正在導致$變量在函數中被重新定義-不再指向jQuery的$()函數。


我在考慮這個:

jQuery(document).ready(function($) {

嘗試使用,而不是:

jQuery(document).ready(function() {

當您遍歷jquery對象時,我相信您必須使用:

$(this).attr('name'); 代替 this.name

同樣,要從對象中調用值,您必須使用$ .val()或$ .attr('attributename');

// Shortcut for doc ready
$(function() 
{ 
 // Loop through values
 var id = $(this).attr('name');

 alert($('input#priceperperson' + id).val());
});

您可能正在尋找.val()嗎?

this.val(parseInt($('priceperperson'+id).val()));

我要提醒的是“對象” ...值是NaN。 我試圖“ parseInt”

嘗試給parseInt一個基數:

parseInt(variable, 10);

有一些錯誤...要獲取jQuery對象的值,必須使用.val()方法,而不是.value

然后,parseInt()需要作為第二個參數的基數。 就像是:

...
this.value = parseInt($('priceperperson'+id).val(), 10) * parseInt($('countpersons'+id).val(), 10); 
...

您的代碼可能包含錯誤

您的代碼ID =長度1如果ID長度> 1可以嗎? 可能的例外

priceperperson1到priceperperson_1

# option # proposal

<input type="text" id="priceperperson_1" name="priceperperson_1" /> // => use "_"
<input type="text" name="personsvalue_1" class="countme" readonly="readonly" />


jQuery(document).ready(function($) {
    $('div.pricerow input.countme').each(function(){ 
        var id = this.name.split("_")[1]; // => get array value 
        this.value = parseInt($('[name=priceperperson_'+id+']').value()) *parseInt($('[name=countpersons='+id+']').value()); 
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM