【问题标题】:Jquery - cannot select the parent divJquery - 无法选择父 div
【发布时间】:2008-12-18 19:14:32
【问题描述】:

我希望这不是浪费时间,但是我一直在努力解决这个问题。是我的语法吗。一旦点击了“.remove-link”类的链接,我只想删除父div“.number-row”。

提前致谢

<script>
$(document).ready(function(){
    $(".remove-link").click(function() {
        $(this).parent(".number-row").hide();
    })
})
</script>

<div class="number-row" >
   <div class="number-column">
         <div class="label-row">
             Select Country:
         </div>
         <div class="input-row">
             <select>
                 <option>1</option>
                 <option>2</option>
             </select>
         </div>
         <div class="label-row">
             Select Toll Free or City:
         </div>
         <div class="input-row">
             <select>
                 <option>1</option>
                 <option>2</option>
             </select>
         </div>
         <div class="label-row">
             Select Your Number:
         </div>
         <div class="input-row">
             <select>
                 <option>1</option>
                 <option>2</option>
             </select>
         </div>
     </div>
   <div class="number-column">
         <div class="label-row">
             Select Country:
         </div>
         <div class="input-row">
             <select>
                 <option>1</option>
                 <option>2</option>
             </select>
         </div>
         <div class="label-row">
             Enter Number to Forward to:
         </div>
         <div class="input-row">
            <input type="text" name="forward_number" id="forward_number" />
         </div>
         <div class="number-row-options">
            <a class="save-link" href="#">Save</a>
            <a class="remove-link" href="#">Remove</a>
         </div>                    
     </div>                    
</div>

【问题讨论】:

  • 该 div 没有“number-row”类的父级
  • @Sleepyhead:它有一个祖先; parent() 和 parents() 的行为之间的常见混淆。

标签: jquery dom


【解决方案1】:

尝试使用parents() 而不是parent():

$(document).ready(function(){
    $(".remove-link").click(function() {
        $(this).parents(".number-row").eq(0).hide();
    })
})

【讨论】:

  • 我通常也会做一个 slice(0, 1) 来获得最接近的匹配父级,尽管使用这样一个特定的选择器可能并不那么重要..
【解决方案2】:

应该这样做...

$(document).ready(function(){ 
    $(".remove-link").click(function() { 
        $(this).parent().parent().parent().hide();
    }) 
})

请注意,这不会删除您要求的;它只是隐藏它。您可以使用 remove() 而不是 hide() 将其从 DOM 中删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 2012-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多