我正在尝试将sweetalert2与自定义html一起使用,其中包含具有我想要访问的数据绑定(bind)的 polymer 元素,但我无法使用“this.attributeName”表示法获取数据。我认为这是由于甜蜜警报被附加到正在创建警报的元素上方的 DOM,但我可能是错的,是否有解决方法?我已经提供了用于创建警报的代码,并且在解决方案中我试图解决这个问题。
swal({
title: 'Blah Blah',
html:
'<some-el id="days" chosen-days="{{newCDays}}"></some-el>\
<time-input id="start" time$="{{newSTime}}" hour12 clamp="seconds"></time-input>\
<time-input id="end" time$="{{newETime}}" hour12 clamp="seconds"></time-input>',
confirmButtonText: 'Done',
preConfirm: function() {
return new Promise((resolve, reject) => {
resolve({
days: document.getElementById('days').getAttribute("chosen-days"),
start: document.getElementById('start').value,
end: document.getElementById('end').time,
});
});
}
});
最佳答案
swal html 中没有数据绑定(bind)
Polymer 数据绑定(bind)仅在 Polymer 模板内工作,因此在 html
中使用该语法swal
领域将导致将文字值分配给属性。在以下示例中,<paper-input>.value
设置为"{{myValue}}"
从字面上看(包括大括号)。请注意,它不会创建 <paper-input>.myValue
.
swal({
html: '<paper-input no-label-float value="{{myValue}}"></paper-input>'
...
})
html
不应包含数据绑定(bind)。它应该看起来像这样:
swal({
html: '<paper-input no-label-float></paper-input>'
...
})
访问元素属性
在 preConfirm
函数,您可以从 html
查询元素字段,并按名称访问该元素的属性:
swal({
preConfirm: async () => {
console.log({
noLabelFloat: document.getElementById('myInput').noLabelFloat
});
}
...
})
原生事件绑定(bind)
在您的 Codepen 中,您表明 <input>
像这样使用:
<input type="text" value$="{{testAttr}}">
基于您在 swal
中的绑定(bind)的html
,我认为您假设上面的数据绑定(bind)会设置 <x-foo>.testAttr
至<input>.value
,但这实际上是不正确的。给定一个本地人 <input>
元素,你必须使用 Polymer 的 native event-binding syntax :
<input type="text" value="{{testAttr::input}}">
设置 <x-foo>.testAttr
至<input>.value
当 <input>
提出input
事件。它相当于:
// in x-foo script
myNativeInput.addEventListener('input', () => {
this.testAttr = myNativeInput.value;
});
关于javascript - 在 Polymer 中不使用 'this.attributeName' 表示法访问数据绑定(bind)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819946/