如何解决将 Jquery 页面附加为 shadow dom 内的 web 组件
我正在尝试使用 Web 组件和 shadow dom 将 Jquery Web 应用程序添加到 Angular 应用程序中
为了存档,我使用了这个脚本
class Legacy2Wc extends HTMLElement {
url = undefined;
parent = undefined
constructor() {
super();
}
connectedCallback() {
parent = this.attachShadow({ mode: 'closed' });
}
static get observedAttributes() {
return ['url'];
}
attributeChangedCallback(name,oldValue,newValue) {
if (name === 'url' && oldValue !== newValue) {
this.url = newValue;
this.render();
}
}
render() {
const context = this;
const xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange',function() {
if (this.readyState === 4) {
context.buildComponent(this.responseText,context);
}
});
xhr.open('GET',this.url);
xhr.send();
}
buildComponent(source,parent) {
const contextualElement = document.createRange().createContextualFragment(source);
parent.append(contextualElement);
}
}
customElements.define('legacy-2-wc',Legacy2Wc);
为了正常工作,我将标签添加到 html
<body>
<legacy-2-wc url="http://some-page-with-jquery.com"></legacy-2-wc>
</body>
我的目标 jquery 应用程序看起来像这样
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Document</title>
</head>
<body>
<table id="jquery-wc-table">
<thead>
<th>id</th>
<th>name</th>
<th>address</th>
<th>date</th>
</thead>
<tbody>
</tbody>
</table>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" type="text/javascript"></script>
<script src="https://rawgit.com/Marak/faker.js/master/examples/browser/js/faker.js" type="text/javascript"></script>
<script type="text/javascript">
faker.seed(1);
const data = new Array(20).fill({}).map(() => ({
id: faker.random.uuid(),name: faker.name.firstName(),address: faker.address.streetAddress(),date: faker.date.past()
}));
const urlParams = new URLSearchParams(window.location.search);
$(document).ready(() => {
const filterData = data.filter(dataItem => {
return !urlParams.has('name') || dataItem.name.toLowerCase().trim().includes(urlParams.get('name').toLowerCase().trim());
});
const table = $('#jquery-wc-table tbody');
table.find('td')
.remove()
.end();
filterData.forEach(dataItem => {
const row = table.append('<tr></tr>');
row.append(`<td>${ dataItem.id }</td>`);
row.append(`<td>${ dataItem.name }</td>`);
row.append(`<td><address>${ dataItem.address }</address></td>`);
row.append(`<td>${ dataItem.date.toISOString() }</td>`);
})
});
</script>
</body>
</html>
当我打开容器应用程序时,我收到错误消息,告诉我未定义 jquery
这就像导入 jquery 的脚本没有做任何事情,或者 jquery 页面的功能无法访问它们
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。