解決關於jquery中$.get()方法總是報“HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy”錯的方法

來源:互聯網
上載者:User

標籤:

解決關於jquery中$.get()方法總是報“HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy”錯的方法

  今天在看《jquery基礎教程(第三版)》第十章的時候,運行隨書下載的源碼時總是不成功。起初以為書中內建的JS檔案有錯呢,但是測來測去也沒發現哪裡有問題。現在把源碼附下:

1、這是書中帶的HTML檔案,其餘的忽略不計,關鍵的就是下面這個a。

<a id="more-photos" href="pages/1.html">More Photos</a>

2、對應的JS檔案如下(注意其中關鍵方法為$.get()):

 1 $(document).ready(function() { 2   var pageNum = 1; 3 $(‘#more-photos‘).click(function() { 4 var $link = $(this); 5 var url = $link.attr(‘href‘); 6 if (url) { 7 $.get(url, function(data) { 8 $(‘#gallery‘).append(data); 9  });10 pageNum++;11 if (pageNum < 20) {12 $link.attr(‘href‘, ‘pages/‘ + pageNum + ‘.html‘);13  }14 else {15  $link.remove();16  }17  }18 return false;19  });20 });

 

3、錯誤。以上看起來似乎沒有問題,但是在Firefox和Chrome下測試都報錯,其中Firefoxdebug錯誤如下:

  整個一章的代碼都是這樣,但是測試在IE裡沒有問題。於是Google、百度各種亂搜一翻,貌似網上發生這樣問題的還不在少數,但是搜來搜去各種回答都 有。一一試了下,發現其中的以為大哥的方法貌似正確,於是查了下jquery api,原來是問題出在$.get()方法上,書中的源碼在使用這個方法的時候都沒有指定這個方法的type參數,即jQuery.get(url, [data], [callback], [type])第四個參數。加上第四個參數‘html’以後就顯示正常了。Okay了!灰常happy!現在運行OK了,已經沒有錯誤了。

  具體方法如下:

  在上面的JS檔案中的第7行$.get()方法上增加一個type參數即可,如下(注意第9行增加了一個‘html’的type參數):

 1 $(document).ready(function() { 2   var pageNum = 1; 3 $(‘#more-photos‘).click(function() { 4 var $link = $(this); 5 var url = $link.attr(‘href‘); 6 if (url) { 7 $.get(url, function(data) { 8 $(‘#gallery‘).append(data); 9 },‘html‘);10 pageNum++;11 if (pageNum < 20) {12 $link.attr(‘href‘, ‘pages/‘ + pageNum + ‘.html‘);13  }14 else {15  $link.remove();16  }17  }18 return false;19  });20 });

  由於是新手,也只找到了怎麼解決這個問題,但是沒有找到為什麼會出現這樣的問題。以後使用$.ajax()\$.get()等這幾個方法的需要注意一下子了。

  參考:http://blog.sina.com.cn/s/blog_995c1f630101a36l.html(這位大哥的錯誤發生在$.ajax()方法上)

解決關於jquery中$.get()方法總是報“HierarchyRequestError: Node cannot be inserted at the specified point in the hierarchy”錯的方法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.