[英]jQuery: on change get closest element?
我正在嘗試使用jquery來獲取輸入字段中最接近的元素,因此我可以使用元素的text / html作為輸入字段的值。
我的jquery看起來像這樣:
<script>
jQuery("[name=currencies]").val(Currency.currentCurrency).change(function() {
$(".moneyPrice").val($(this).closest('.mypro').find($("span.money").text()));
});
</script>
span.money
是動態創建的。
我的HTML看起來像這樣:
<div align="center" class="mypro" style="position:relative; width:270px; height:570px; border:solid 1px #CCC; margin:10px; float:left; overflow:hidden; padding:5px;">
<a class="overlay" href="product.php"></a>
<!--<a class="overlayBtns" href="">Quick View</a>-->
<a class="overlayAdd" href="javascript:{}" onclick="form'.$id.'.submit();"><i class="fa fa-shopping-cart"></i>
Add To Basket</a>
<img width="100%" src="product_images/'.$id.'Image1.jpg" alt="" />
<p style="padding:2px;">'.$product_name.'</p>
<p style="padding:2px;">'.$manu.'</p>
<div style="padding:5px;" class="price">
<div class="prod-price"><span class=money>£'.$price.'.00</span></div>
<form id="form'.$id.'" name="form1" method="post" action="cart.php">
<input type="hidden" name="pid" id="pid" value="'.$id.'" />
<input type="text" name="" class="moneyPrice" value="" />
</form>
</div>
</div>
上面的HTML代碼也是使用PHP dynamically
創建的。
所以基本上,當select選項改變時,我的jquery代碼會激活。 但是我在輸入字段[object object]
得到了這個。
如果我將我的jquery代碼更改為:
$(".moneyPrice").val($("span.money").text());
它將在我的輸入字段中顯示span.money
文本,但問題是它將在所有輸入字段中顯示所有動態創建的span.money文本。
因此,我需要獲得最接近的span.money
,到.moneyPrice
輸入字段,然后將span.money顯示到最接近的.moneyPrice
輸入字段中。
對不起,如果這有點令人困惑,我希望我得到你們的幫助。
任何幫助,將不勝感激。
編輯:
<select id="currencies" name="currencies">
<option value="GBP" selected="selected">GBP</option>
<option value="USD" >USD</option>
<option value="NGN">NGN</option>
<!--<option value="AUD">AUD</option>
<option value="SGD">SGD</option>-->
<option value="EUR">EUR</option>
</select>
編輯:
我已經創建了一個工作jsfiddle,所以你可以看到問題:
您的語法不太正確,可能是因為嘗試在一行中做太多
$(".moneyPrice").val($(this).closest('.mypro').find($("span.money").text()));
應該
$(".moneyPrice").val($(this).closest('.mypro').find("span.money").text());
請注意,您的find()將與之相同
var txt = $("span.money").text();// is not a selector
find(txt) // returns jQuery object not a text value but `txt` isn't a valid selector either
你需要做的就是改變
$(".moneyPrice").val($(this).closest('.mypro').find($("span.money").text()));
至
$(".moneyPrice").val( $(this).closest('.mypro').find("span.money").text() );
我還注意到html代碼中的一些重大錯誤。 當在html代碼中有變量時,你必須用“php start”和“php end”來表達它們。
就像是...
我想<?php echo $nr_of_icecreams;?>
冰淇淋
不
我想要$nr_of_icecreams
,這似乎是你在代碼中所做的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.