【问题标题】:get the previous element value with jquery用jquery获取前一个元素值
【发布时间】:2013-07-03 20:33:16
【问题描述】:

我有一个 wordpress 页面,上面显示了带有 ajax 添加到购物车操作的产品。单击按钮时,我想获取名称=数量的输入值。我想用 jquery prev() 函数来做到这一点,因为有许多其他具有相同属性的输入。那么我该怎么做呢?我有

jQuery(document).ready(function(e){
     e(document).on("click",".add_to_cart_button",
          function(){
          var t=e(this);   
})})



<form action="/shop/?add-to-cart=1732" class="cart" method="post" enctype="multipart/form-data">
    <div class="quantity buttons_added">
       <input type="button" value="-" class="minus">
       <input type="number" step="1" name="quantity" value="1" title="Qty" class="input-text qty text">
       <input type="button" value="+" class="plus">
    </div>
    <button type="submit" data-product_id="1732" data-product_sku="menu-aug-02" data-quantity="1" class="add_to_cart_button button product_type_simple">Add to cart</button></form>

【问题讨论】:

  • 你参考了哪个元素?

标签: jquery html ajax forms


【解决方案1】:

试试这个

$('input[type=submit]').click(function() {
    ...
    ...

    var prevInput = $(this).prev().children('input[name=quantity]');    // This is what you need


    // Try with this 
    var requiredInput;
    $(this).prev().children().each(function() {
        if($(this).attr('name') != null)
        {
            requiredInput = $(this);
        }
    });

    ...
    ...
});

API
prev()
children()

【讨论】:

  • 你需要'提交'或'加号'上的点击事件——我猜加号只是为了扩展一些细节?是吗?
  • 我想要输入的文本而不是它的值!
  • “输入的文本”是什么意思?
  • 我的意思是输入框中看到的值!正负值正在改变!
【解决方案2】:

试试看

$('.plus').on('click',function(){
     var qty = $('input[name="quantity"]').val();
     alert(qty);
});

你也可以试试.before()like

$('.plus').on('click',function(){
     var qty = $(this).before('input[name="quantity"]').val();
     alert(qty);
});

.prev()点赞

$('.plus').on('click',function(){
     var qty = $(this).prev('input[name="quantity"]').val();
     alert(qty);
});

如果你想在提交时尝试一下

$('.cart').on('submit',function(e){
     e.preventDefault();
     var qty = $(this).prev('input[name="quantity"]').val();
     alert(qty);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多