![](/img/trans.png)
[英]How to build a list of objects from JQuery selectors and send in Ajax post
[英]How to build hierarchical objects with siblings tags using jquery selectors
我有以下html片段。 我想通過網絡抓取頁面以獲取主題和子主題並將其存儲在對象中。
所需的結果是:
{
'topic': 'Java Basics',
'subtopics':['Define the scope of variables', 'Define the structure of a Java class', ...]
}
我試圖使其與Jsdom for Node.js和JQuery一起使用:
var jsdom = require('jsdom');
var fs = require("fs");
var topicos = fs.readFileSync("topic.html", "utf-8");
jsdom.env(topicos, ["http://code.jquery.com/jquery.js"], function (error, window) {
var $ = window.$;
var length = $('div ~ ').each(function () {
//???
var topic = $(this);
var text = topic.text();
console.log(text.trim())
});
})
但是由於缺乏jQuery的經驗,我無法正確組織層次結構。
HTML片段:
<div>
<strong>Java Basics </strong></div>
<ul>
<li>
Define the scope of variables </li>
<li>
Define the structure of a Java class
</li>
<li>
Create executable Java applications with a main method; run a Java program from the command line; including
console output.
</li>
<li>
Import other Java packages to make them accessible in your code
</li>
<li>
Compare and contrast the features and components of Java such as:
platform independence, object orientation, encapsulation, etc.
</li>
</ul>
<div>
<strong>Working With Java Data Types </strong></div>
<ul>
<li>
Declare and initialize variables (including casting of primitive data types)
</li>
<li>
Differentiate between object reference variables and primitive variables
</li>
<li>
Know how to read or write to object fields
</li>
<li>
Explain an Object's Lifecycle (creation, "dereference by reassignment" and garbage collection)
</li>
<li>
Develop code that uses wrapper classes such as Boolean, Double, and Integer. </li>
</ul>
...
這是工作片段提琴
var topicos = [];
jQuery('div').each(function(){
var data = {};
var jThis = jQuery(this);
data.topic = jThis.find('strong').text();
data.subtopics = [];
jThis.next('ul').find('li').each(function(){
var jThis = jQuery(this);
data.subtopics.push(jThis.text());
});
topicos.push(data);
});
console.log(topicos);
但我強烈建議您將類添加到您的標記中,並將其用作選擇器而不是標記名:
<div class="js-topic-data">
<div>
<strong class="js-topic">Java Basics </strong>
</div>
<ul>
<li class="js-sub-topic">
Define the scope of variables </li>
<li>
</ul>
</div>
然后,您可以執行以下操作:
jQuery('.js-topic-data').each(function(){
var data = {};
var jThis = jQuery(this);
data.topic = jThis.find('.js-topic').text();
data.subtopics = [];
jThis.next('.js-sub-topic').each(function(){
var jThis = jQuery(this);
data.subtopics.push(jThis.text());
});
topicos.push(data);
});
這對於標記更改等更為健壯
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.