我有带有Alpine.js组件的Html。我希望能够克隆它(使用jQuery)。不幸的是,它不起作用--当使用x-for时,我得到:
ReferenceError:未定义选项
事实上,有些元素内容是重复的(“一二三”每段显示两次)
显然,这里的代码是简化的(实际上,我想用更多的组件方法克隆自定义下拉列表),但是我相信简单的代码清楚地显示了问题。
Html代码:
<div>
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</div>
<button>Clone element</button>JavaScript代码:
const CustomComponent = (function() {
return {
options: [],
initialize()
{
this.options = ['one', 'two', 'three'];
}
}
}());
$('button').on('click', function() {
$('div').append($('p').first().clone());
});发布于 2020-09-24 18:20:37
解决方案似乎是在克隆之前不解析元素的副本:
Html:
<div>
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</div>
<button>Clone element</button>
<template class="tpl">
<p x-data="{...CustomComponent}" x-init="initialize()">
<template x-for="option in options">
<span x-text="option"></span>
</template>
</p>
</template>JavaScript:
const CustomComponent = (function() {
return {
options: [],
initialize()
{
this.options = ['one', 'two', 'three'];
}
}
}());
$('button').on('click', function() {
$('div').append($('template.tpl').html());
});https://stackoverflow.com/questions/64049646
复制相似问题