2016-06-23 171 views
1

我遇到了通過jQuery選擇下一個提交按鈕的問題。觸發下一個提交按鈕

我有這樣的事情:

$('.description-part').on('change', 'textarea', function() { 
 
    $(this).find('.button').addClass('test'); // not working 
 
    $(this).next('.button').addClass('test'); // not working 
 
    $(this).closest('.button').addClass('test'); // not working 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="description-part"> 
 
    ... 
 
    <textarea></textarea> 
 
    <div></div> 
 
    <input type="submit" name="save" class="button"> 
 
    ... 
 
</div>

回答

3

只需使用nextAll()作爲thistextarea,而不是div,你在textareabutton之間有<div>,所以.next()韓元不管用:

$('.description-part').on('change', 'textarea', function() { 
    $(this).nextAll('.button').addClass('test'); 
}); 

或者您可以使用.closest()這樣:

$('.description-part').on('change', 'textarea', function() { 
    $(this).closest('.description-part').find('.button').addClass('test'); 
}); 

工作摘錄

$(function() { 
 
    $('.description-part').on('change', 'textarea', function() { 
 
    $(this).closest('.description-part').find('.button').addClass('test'); 
 
    }); 
 
});
.test {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="description-part"> 
 
    ... 
 
    <textarea></textarea> 
 
    <div></div> 
 
    <input type="submit" name="save" class="button" />... 
 
</div>

$(function() { 
 
    $('.description-part').on('change', 'textarea', function() { 
 
    $(this).nextAll('.button').addClass('test'); 
 
    }); 
 
});
.test {background: red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="description-part"> 
 
    ... 
 
    <textarea></textarea> 
 
    <div></div> 
 
    <input type="submit" name="save" class="button" />... 
 
</div>