2013-11-15 143 views
0

我已經使用jQuery Mobile的,我已經得到了以下簡單的問題一個頁面:jQuery的不刪除元素

與DOM的某處(單)鏈接的頁面時:

<a data-theme="a" data-role="button" href="https://m.mybet.com"> 
Smartphone-Version nutzen</a> 

我加入這樣一個按鈕HTML

<input type="button" onclick="javascript:remove_link();"/> 

我的JavaScript看起來像這樣:

<script type="text/javascript"> 
    function remove_link() { 
     console.log("1") 
     $("a").remove(); 
     console.log("2") 
    } 
</script> 

但是,單擊該按鈕時,Chrome瀏覽器告訴我:

Uncaught TypeError: Cannot call method 'remove' of null 
remove_link 
onclick 

我也嘗試空()來代替,同樣的問題。爲什麼?

+0

小心創建[fiddle](http://jsfiddle.net)? – Chandranshu

+1

是正確包含在頁面中的jQuery?如果你在控制檯輸入$('a'),你會得到什麼? – opalenzuela

+0

它在這裏工作:http://jsfiddle.net/Q7kJd/ – melancia

回答

0

好吧,我發現了。我現在使用原生的javacript:

document.querySelector('a').remove() 

完成這項工作。

0

我總是使用javascript的id,對我來說更簡單。試試這個:

<a data-theme="a" id="id1" data-role="button" href="https://m.mybet.com"> 
Smartphone-Version nutzen</a> 

<script type="text/javascript"> 
    function remove_link() { 
     console.log("1") 
     $("#id1").remove(); 
     console.log("2") 
    } 
</script> 
0

試試這個:

<a data-theme="a" data-role="button" href="https://m.mybet.com"> 
Smartphone-Version nutzen</a> 

<input id="remove_link" type="button" /> 

<script type="text/javascript"> 
    $('#remove_link').click(function() { 
    console.log("1") 
    $("a").remove(); 
    console.log("2") 
    }); 
</script> 
0

看起來你還沒有加載jQuery的。確保在調用您的功能之前包含<script src="path/to/jquery.js"></script>

如果不加載jQuery,您的瀏覽器正在調用本地$函數。

// native jQuery function 
function $(id) { 
    return document.getElementById(id); // may return null 
} 

本地函數可以返回null代替空jQuery對象。它也在搜索一個id,而不是一個css選擇器。在你的情況下,一個id爲'a'而不是所有錨元素的元素。