2013-11-15 145 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'而不是所有锚元素的元素。