【问题标题】:jQuery parsing html into JSONjQuery 将 html 解析为 JSON
【发布时间】:2013-08-18 02:57:26
【问题描述】:

我目前正在使用以下代码:

jQuery('#book-a-service').click(function(){
 var selectedServices = jQuery('.selected').parent().parent().html();       
 console.log(selectedServices);
});

然后返回:

<td rowspan="3">Brakes</td>
  <td class="service-title">BRAKES SET</td>
  <td class="service-description"><p>Setting of front and rear brakes for proper functioning (excluding bleeding)</p></td>
  <td class="service-price">R <span id="price-brakes-set">R75</span><div id="select-brakes-set" class="select-service selected"></div>
</td>

这就是我想要的,除了我需要 JSON 中带有“.selected”类的所有元素的数组。 td 标签和“服务价格”只有数值,然后我将如何将这些值插入到 json 对象中?

非常感谢任何帮助..

【问题讨论】:

  • "elements" 是 XML 节点,不能转换为 JSON。您到底想要什么,将一些文本内容作为字符串数组获取?请发布预期结果。
  • 这里是a jsFiddle,带有此代码以及正常运行所需的周围标签。

标签: javascript jquery json


【解决方案1】:

jQuery 不是我最强大的框架,但这似乎可以解决问题。

jQuery('#book-a-service').click(function(){
    var selected = jQuery('.selected');
    selected.each( function() {
        var children = jQuery(this).parent().parent().find('td');
        var json = {};
        console.log(children);
        json.type = jQuery(children[0]).text();
        json.title = jQuery(children[1]).text();
        json.description = jQuery(children[2]).find('p').text();
        json.price = jQuery(children[3]).find('span#price-brakes-set').text();
        console.log(json);
        console.log(JSON.stringify(json));
    });
});

在行动:http://jsfiddle.net/3n1gm4/DmYbb/

【讨论】:

  • 嘿,非常感谢.. 但是如果它在多个“选择”的地方我会怎么做?
  • 您可以在jQuery('.selected') 上使用.each() 函数,然后使用jQuery(this) 代替.parent().parent() 字符串并进行一些小的调整api.jquery.com/each 我已经更新了小提琴
  • 也更新了答案
【解决方案2】:

当多个元素共享同一个类并且您使用 $(".class") 选择它们时,您可以使用以下方法遍历所有元素:

$(".selected").each(function() {
    var element = $(this); // This is the object with class "selected" being used in this iteration
    var absoluteParent = $(this).parent().parent();

    // Do whatever you want...

    var title_element = $(".service-title", absoluteParent); // Get service-title class elements in the context provided by "absoluteParent", I mean, "inside" of absoluteParent
    var title = title_element.html();
});

在价格的具体情况下,我不知道确切的价格是多少(可能是R75?)。无论如何,它应该在一个 div 内,然后选择该 div 以获取价格。如果是 R75,请注意“id”属性对于 HTML 中的每个 DOM 对象应该是唯一的。

另外请注意,在获取 HTML 时,您只是获取一个字符串,而不是实际的元素,因此它对于以简单的方式获取新值可能没有用处(您不会无法使用普通字符串浏览 DOM 元素,即使它表示来自实际对象的 HTML)。始终获取 jQuery 对象并使用它们,除非您确实需要 HTML。

要生成 JSON 字符串,只需创建一个全局数组并在其中添加您需要的对象/值。然后你可以使用var jsonText = JSON.stringify(your_array);获取一个JSON字符串

考虑不要在 Javascript 中这样做,因为它在大多数情况下没有用。只需通过 POST 值将值发送到脚本(例如 PHP),然后在 PHP 中您将获得实际值。另一种方式(PHP 到 Javascript)将有助于返回 JSON(使用 json_encode($a_php_array)),然后在 Javascript 中使用 var my_array = JSON.parse(the_string_returned_by_php); 转换为 JS 数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2010-12-31
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多