2017-10-20 92 views
-2

我對jQuery相當陌生,遇到了一些問題。這些代碼片段有什麼區別?我認爲他們會做同樣的事情。這兩個jQuery代碼片段有什麼區別?

$("p.expendable").on('mouseover', function(){ 
 
    $(this).remove(); 
 
}); 
 

 
$('p').on('mouseover', function() { 
 
    $('p.expendable').remove(); 
 
});

+0

我不知道你想做什麼。 OnMouseOver =>刪除自己? –

+0

兩者都不同! –

+0

問題是,哪個代碼是正確的 –

回答

-1

代表是清潔

$(document).delegate("p.expendable", 'mouseover', function(){ 
    $(this).remove(); 
}); 

它說,如果創建p.expendable,附加功能,它是刪除自身。 (不建議使用!)在這一個良好的漁獲@epascarello

請使用

$(document).on("p.expendable", 'mouseover', function(){ 
     $(this).remove(); 
    }); 

或只是

$("p.expendable").on('mouseover', function(){ 
      $(this).remove(); 
     }); 

編碼愉快!

+1

非常感謝! –

+0

如果您只希望特定元素中的段落具有上述功能,請確保將文檔更改爲您所需的父元素。 –

+1

是使用不推薦的方法總是更清潔...大聲笑這也不回答這個問題。 – epascarello

1

它們是不同的。

考慮到第一種情況,如果當前盤旋的p元素有expendable類,那麼它將刪除該特定元素。

$("p.expendable").on('mouseover', function() { 
 
    $(this).remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p class="expendable"> Testing</p> 
 
<p> Testing 2</p> 
 
<p> Testing 3</p>

在第二種情況下,目前懸停的元件是任何p標籤而不管其是否具有任何類或沒有,那麼它會刪除所有p元件,其具有「消耗」類

$('p').on('mouseover', function() { 
 
    $('p.expendable').remove(); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p class="expendable"> Testing</p> 
 
<p> Testing 2</p> 
 
<p> Testing 3</p>