You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Web Components场景下jQuery等效document.createElement的实现及属性丢失问题

jQuery操作Web Components自定义元素的正确实现方式

问题根源:你代码里的$masonry是jQuery对原生DOM元素的包装对象,不是DOM元素本身。直接给$masonry挂载items、width、height等属性,只会保存在jQuery实例上,自定义组件本身无法读取到这些配置。

原生代码对应的jQuery等价实现

// 创建自定义元素的jQuery包装实例
const $masonry = $('<test-horizontal-masonry></test-horizontal-masonry>');
// 取出原生DOM节点,给组件挂载配置属性
const masonryEl = $masonry[0];
masonryEl.items = [
    {
        id: `0`,
        url: "https://homepages.cae.wisc.edu/~ece533/images/watch.png",
        isPremium: false,
        alt: 'Thumbnail'
    },
    {
        id: `1`,
        url: "https://homepages.cae.wisc.edu/~ece533/images/baboon.png",
        isPremium: true,
        alt: 'Thumbnail'
    },
    {
        id: `2`,
        url: "https://homepages.cae.wisc.edu/~ece533/images/cat.png",
        isPremium: true,
        alt: 'Thumbnail'
    }
];
// 绑定自定义事件,jQuery监听的事件原始参数存放在originalEvent中
$masonry.on('THUMBNAIL_CLICK_EVENT', (e) => {
    // 对应原生的 e.detail.item
    const item = e.originalEvent.detail.item;
});
// 插入到页面中
$('body').append($masonry);

你尝试的代码修正版

$masonry = $('<theo-horizontal-masonry rows="1"></theo-horizontal-masonry>');
// 取出原生DOM节点后再赋值属性
const masonryEl = $masonry[0];
masonryEl.items = items;
masonryEl.width = 256;
masonryEl.height = 100;
$carousel.append($masonry);

注意事项

  • 字符串类型的普通属性可以用jQuery的.attr()方法赋值,比如$masonry.attr('rows', 1)
  • 数组、对象这类引用类型的自定义属性,必须挂载到原生DOM节点上才能被自定义组件识别
  • 用jQuery监听自定义元素的自定义事件时,原生事件的detail参数需要从e.originalEvent.detail获取

内容的提问来源于stack exchange,提问作者Chris Hansen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 10:12:03