[英]JavaScript/jQuery - Get value of span of current element
所以我有一些<select>
元素,它的每個可能的選項都有一個跨度內的價格。 我遍歷所有選擇標簽,我需要為每個標簽獲取所選選項的跨度值。 所以這是我的代碼
<select class="form-control config-option" id="s{{ $availableCategory->index}}">
<option>{{ $availableCategory->default_option }}</option>
@foreach($availableOptions as $availableOption)
@if($availableOption->category->name == $availableCategory->name)
<option>({{ $availableOption->code }}) {{ $availableOption->name }} <span class="option-price">({{ $currency == 'EUR' ? 'EUR' : 'USD'}} {{ $availableOption->price }})</span></option>
@endif
@endforeach
</select>
我試圖通過 jQuery 的find()
函數按類和標簽名訪問它,但我沒有這樣做。
$('.config-option').each(function() {
var currentElement = $(this);
var optionPrice = currentElement.find('.option-price');
console.log(optionPrice);
});
如果我控制台日志optionPrice.val()
我得到未定義。 那么我怎樣才能訪問這個跨度呢? 有沒有更好的方法來做到這一點? 使用純 JavaScript 的解決方案也可以。
你不應該在選項標簽內放置標簽,說試試這個
$('.config-option').each(function() {
var currentElement = $(this);
var optionPrice = currentElement.find('.option-price').parent().text();
console.log(optionPrice);
});
更新:跨度標簽被瀏覽器刪除所以使用這個標記結構
<select>
<option data-price="PRICE_HERE">
然后在js中使用它
$('.config-option option:selected').each(function() {
var optionPrice = $(this).attr('data-price');
console.log(optionPrice);
});
spans 沒有 value 屬性(只有輸入具有該屬性),因此您需要從 span 中獲取 .text()
$('.config-option').each(function() {
var currentElement = $(this);
var optionPrice = currentElement.find('.option-price').text();
console.log(optionPrice);
});
但是你為什么不直接循環並專門選擇 .option-price 呢?
$('.option-price').each(function() {
var optionPrice = $(this).text();
console.log(optionPrice);
});
optionPrice.val()
用於input
字段。
您需要調用optionPrice.text()
而不是 this。
嘗試這個
console.log(optionPrice.text());
您可以為選擇框的選項添加值,然后您將很容易獲得該值
<select class="form-control config-option" id="s{{ $availableCategory->index}}">
<option>{{ $availableCategory->default_option }}</option>
@foreach($availableOptions as $availableOption)
@if($availableOption->category->name == $availableCategory->name)
<option value="({{ $currency == 'EUR' ? 'EUR' : 'USD'}} {{ $availableOption->price }})">({{ $availableOption->code }}) {{ $availableOption->name }} <span class="option-price">({{ $currency == 'EUR' ? 'EUR' : 'USD'}} {{ $availableOption->price }})</span></option>
@endif
@endforeach
</select>
腳本
$('.config-option').each(function() {
var currentElement = $(this);
// Now you will be able to use val() function
var optionPrice = currentElement.find('.option-price').val();
console.log(optionPrice);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.