Javascript jquery-获取不同的页面元素

Javascript jquery-获取不同的页面元素,javascript,jquery,Javascript,Jquery,我想获取属于其他html页面的元素属性值 例如,如果我在文件a.html中,希望从a.html中的b.html中获取类似元素属性值的数据 我在jquery中所做的一切 请建议 我读过一些帖子,但我想看看下面的内容- 类似-> [a.html的代码] var result = get(b.html).getTag(img).getAttribute(src)//not getting exactly $("#id").append(result) 知道如何实现这一点吗?使用jQuery,您只能加

我想获取属于其他html页面的元素属性值

例如,如果我在文件a.html中,希望从a.html中的b.html中获取类似元素属性值的数据

我在jquery中所做的一切

请建议

我读过一些帖子,但我想看看下面的内容-

类似->
[a.html的代码]

var result = get(b.html).getTag(img).getAttribute(src)//not getting exactly
$("#id").append(result)

知道如何实现这一点吗?

使用jQuery,您只能加载部分远程页面。基本语法:

$('#result').load('ajax/test.html #container');

字符串的第二部分是基本jQuery选择器。请参阅。

首先,您必须获取
b.html
,然后才能找到属性值,例如

//if you dont want to display the data make the div hidden
      ^
$("#someDivID").load("b.html",function(data){

var value=$(data).find("#elementID").attr("attributeName");
});

默认情况下,选择器从文档根开始在DOM中执行搜索。
如果要传递备用上下文,可以将可选的第二个参数传递给$()函数。例如

$('#name',window.parent.frames[0].document.attr()


请记住,您通常只能进行直接连接(如使用
$(..)。加载(
)到您当前所在的同一域上的页面,或加载到没有CORS限制的域。(绝大多数站点都有CORS限制)。如果要从具有CORS限制的跨域页面加载内容,则必须通过服务器发出请求,并让服务器向其他站点发出请求,然后用响应响应前端脚本

对于这个问题,如果您想在不使用jQuery的情况下获得这个结果,您可以在响应文本上使用DOMParser,将其转换为文档,然后您可以在该文档上使用DOM方法来检索元素,根据需要对其进行解析,并将其(或从中检索的数据)插入当前页面。例如:

fetch('b.html') // replace with the URL of the external page
  .then(res => res.text())
  .then((responseText) => {
    const doc = new DOMParser().parseFromString(responseText, 'text/html');
    const targetElementOnOtherPage = doc.querySelector('img');
    const src = targetElementOnOtherPage.src;
    document.querySelector('#id').insertAdjacentHTML('beforeend', `<img src="${src}">`);
  })
  .catch((err) => {
    // There was an error, handle it here
  });
fetch('b.html')//替换为外部页面的URL
。然后(res=>res.text())
.然后((responseText)=>{
const doc=new DOMParser().parseFromString(responseText,'text/html');
const targetelementotherpage=doc.querySelector('img');
const src=targetelementotherpage.src;
document.querySelector(“#id”).insertAdjacentHTML('beforeend',``);
})
.catch((错误)=>{
//有个错误,在这里处理
});

值得注意的是,整个页面都被请求,元素选择过程发生在客户端。