javascript - 用jquer怎么提取这个页面的信息并返回一个json形式
巴扎黑
巴扎黑 2017-04-11 09:02:57
[JavaScript讨论组]
<body>
    <p class="wrap">
        <img src="../img/head1.jpg" alt="">
        <h6>外星人</h6>
        <p>来自外星的外星人</p>
    </p>
    <p class="wrap">
        <img src="../img/head2.jpg" alt="">
        <h6>外星人2</h6>
        <p>来自外星的外星人2</p>
    </p>
    <p class="wrap">
        <img src="../img/head3.jpg" alt="">
        <h6>外星人3</h6>
        <p>来自外星的外星人3</p>
    </p>
    <input type="button" value="获取">
</body>

问下用jQuery怎么获取每个wrap下面img的src值,h6的文本,p的文本?
并返回成这样的结构

[{pos: ../img/head1.jpg, name: 外星人, content:来自外星的外星人},{pos: ../img/head2.jpg, name: 外星人2, content:来自外星的外星人2},{pos: ../img/head3.jpg, name: 外星人3, content:来自外星的外星人3}]
巴扎黑
巴扎黑

全部回复(3)
天蓬老师
var result=[];
$(".wrap").each(function(i,item){
    result.push(
    {
        pos:$(item).find("img").attr("src"),
        name:$(item).find("h6").html(),
        content:$(item).find("p").html()
    
    });
})

console.log(result);

自己可以参考手册多练练~

PHP中文网
$(".wrap").each(function(i,dom){
    var $this = $(dom),
        pos = $this.children("img").attr("src"),
        name = $this.children("h6").text(),
        content = $this.children("p").text();
    str.push({pos:pos,name:name,content:content});
});

巴扎黑
    var res = [];
        $('.wrap').each(function(){
            res.push({
                pos:$('img',this).attr('src'),
                name:$('h6', this).text(),
                content:$('p',this).text()
            })
        })
    console.log(res)

题外话,这样的东西用模板或者Vue之类的框架要简单很多 \(^o^)/~

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号