這是我的代碼:Get請求不記錄任何
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log($(onWebsite).find('.name.notranslate')[0].attr("href"));
});
每當我運行它,它不會記錄到控制檯,所有它說的是:「對象{readyState的:1}」。但是,如果我刪除.attr(「href」),它就會起作用。我的語法有什麼問題嗎?
這是我的代碼:Get請求不記錄任何
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log($(onWebsite).find('.name.notranslate')[0].attr("href"));
});
每當我運行它,它不會記錄到控制檯,所有它說的是:「對象{readyState的:1}」。但是,如果我刪除.attr(「href」),它就會起作用。我的語法有什麼問題嗎?
由於.attr()
是一個jQuery函數,您需要將其與jQuery對象一起使用。
使用
$(onWebsite).find('.name.notranslate').attr("href")
根據你當前的代碼$(onWebsite).find('.name.notranslate')[0]
將返回不具有.attr()
方法DOM元素底層。
可以使用href
屬性或方法Element.getAttribute()
$(onWebsite).find('.name.notranslate')[0].href
OR
$(onWebsite).find('.name.notranslate')[0].getAttribute('href')
這個作品,謝謝! –
如果我想要獲得列表中的下一個項目,該怎麼辦? –
@RobertMaron,你可以使用http://api.jquery.com/each/迭代jQuery objcet – Satpal
也許嘗試:
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log(onWebsite.find('.name.notranslate')[0].attr("href"));
});
onWebsite不能與jQuery選擇作爲其從一個函數返回包裹。
同樣的事情發生。 –
我們來試試這個方法:
var a;
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
a = $(onWebsite).find('.name.notranslate')[0];
console.log(a);
});
您將得到
<a class="name notranslate" href="/Headless-Horseman-item?id=134082613" title="Headless Horseman">Headless Horseman</a>
所以var a是帶有href屬性的HTML標籤。 HTML標籤沒有jQuery方法 - 從DOM或 「包裝/ HTML選擇」
這裏只選擇了jQuery的對象,您可以:
.href
得到HREFa
jQuery中得到:$(a).attr('href')
所以最終代碼將是(變體1越好):
var a;
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
a = $(onWebsite).find('.name.notranslate')[0].href
console.log(a);
});
或不創建臨時變量
$.get("http://www.roblox.com/catalog/", function(onWebsite) {
console.log($(onWebsite).find('.name.notranslate')[0].href);
});
的確實發現返回一個或多個對象的列表? –
一個對象,因爲我將節點設置爲[0]。 –
'[0]'返回沒有任何'attr()'方法的DOM節點 –