[英]trouble with jquery and traversing the DOM to select the appropriate elements
大家好,我在我的網站上有以下html產品清單,
它會顯示一行,其中包含產品標題,價格,所需數量和一個名為購買的復選框。 目前已禁用數量輸入。
所以我想做的是, 如果單擊復選框,我希望將輸入數量設置為1,並且希望它啟用。
我這樣做似乎有些麻煩。 誰能幫忙現在我可以有多個產品,即我的html頁面中將有多個table-products div。
我嘗試使用jQuery更改詳細信息,但我似乎無法訪問某些元素。
因此,基本上,對於每個表格產品,我想在復選框上設置一個單擊偵聽器,以設置輸入文本(即qty文本字段)的值。
所以下面的頁面上可能有20個。
<div class="table-products">
<div class="table-top-title">
My Spelling Workbook F
</div>
<div class="table-top-price">
<div class="price-box">
<span class="regular-price" id="product-price-1"><span class="price">€6.95</span></span>
</div>
</div>
<div class="table-top-qty">
<fieldset class="add-to-cart-box">
<input type="hidden" name="products[]" value="1"> <legend>Add Items to Cart</legend> <span class="qty-box"><label for="qty1">Qty:</label> <input name="qty1" disabled="disabled" value="0" type="text" class="input-text qty" id="qty1" maxlength="12"></span>
</fieldset>
</div>
<div class="table-top-details">
<input type="checkbox" name="buyMe" value="buy" class="add-checkbox">
</div>
<div style="clear:both;"></div>
</div>
這是我嘗試過的JavaScript
jQuery(document).ready(function() {
console.log('hello');
var thischeck;
jQuery(".table-products").ready(function(e) {
//var catTable = jQuery(this);
var qtyInput = jQuery(this).children('.input-text');
jQuery('.add-checkbox').click(function() {
console.log(jQuery(this).html());
thischeck = jQuery(this);
if (thischeck.is(':checked'))
{
jQuery(qtyInput).first().val('1');
jQuery(qtyInput).first().prop('disabled', false);
} else {
}
});
});
// Handler for .ready() called.
});
采用
jQuery('.add-checkbox').change(function() {
問題是一方面您觀察到單擊而不更改,所以請使用更改,因為它實際上是在狀態更改后觸發的
var qtyInput = jQuery(this).children('.input-text');
另一件事是,輸入不是.table-products的直接子代
看到這個小提琴
不是最直接的方法,但這應該可行。
jQuery(document).ready(function() {
jQuery('.add-checkbox').on('click', function() {
jQuery(this)
.parents('.table-products')
.find('input.input-text')
.val('1')
.removeAttr('disabled');
});
});
jQuery('input:checkbox.add-checkbox').on('change', function() {
jQuery(this)
.parent()
.prev('div.table-top-qty')
.find('fieldset input:disabled.qty')
.val(this.checked | 0)
.attr('disabled', !this.checked);
});
這應該使您朝正確的方向開始。 基於jQuery 1.7.2(我看到了您的prop調用,並且猜測那是您正在使用的)。
$(document).ready(function() {
var thischeck;
$('.table-products').on('click', '.add-checkbox', function() {
var qtyInput = $(this).parents('.table-products').find('.input-text');
thischeck = $(this);
if (thischeck.prop('checked')) {
$(qtyInput).val('1').prop('disabled', false);
} else {
$(qtyInput).val('0').prop('disabled', true);
}
});
});
由於某種原因刪除該屬性會導致無法重新添加該屬性。 這適用於多個表。 對於您的沖突,只需將$替換為jQuery。
這是小提琴: http : //jsfiddle.net/KqtS7/5/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.