我正在尝试使用模板/ html本身中封装/引用的大多数javascript创建自定义元素。我如何从模板/元素中使该javascript在影子dom中执行?下面是一个示例,可以更好地理解此问题。如何使template.innerHTML
(<script>alert("hello"); console.log("hello from tpl");</script>
)中的脚本执行?
目前我没有任何警报或登录控制台。我正在使用Chrome浏览器进行测试。
class ViewMedia extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'closed'});
var template = document.createElement( 'template' );
template.innerHTML = '<script>alert("hello"); console.log("hello from tpl");</script>';
shadow.appendChild( document.importNode( template.content, true ) );
}
}
customElements.define('x-view-media', ViewMedia);
答案 0 :(得分:0)
几点:
$.ajax({
type: "POST",
url: '',
data: {
Name: value
},
success: function (data, status, xhr) {
for (var s = 0; s < marker1.length; s++) {
map.removeLayer(marker1[s]);
}
for (var i = 0; i < data.length; i++) {
var value = i + 1;
if (circle[i].contains(L.latLng([data[i].Latitude, data[i].Longitude]))) {
var customPopup1 = 'Station: ' + data[i].StationName;
var customOptions1 =
{
'maxWidth': '500',
'className': 'custom'
};
circle[i].bindPopup(customPopup1, customOptions1);
}
else {
marker1[i] = L.marker([data[i].Latitude, data[i].Longitude]).addTo(map);
var customPopup = 'Latitude: ' + data[i].Latitude + '</br>Longitude: ' + data[i].Longitude
+ '</br>Station: ' + data[i].StationName + ' </br>Box: ' + data[i].Name + '</br>Timestamp: ' + data[i].LocationSend
+ `<br/><a href='/Home/History?DeviceID=${value}'>Click here for Location History</a><br/>`;
marker1[i].bindPopup(customPopup);
}
}
setTimeout(function () { getCookie("Token", variable); }, 10000);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
添加脚本您可以使用
innerHTML
创建脚本块,然后将它们添加为子元素。
var el = document.createElement('script');
class ViewMedia extends HTMLElement {
constructor() {
super();
const shadow = this.attachShadow({mode: 'closed'});
const s = document.createElement('script');
s.textContent = 'alert("hello");';
shadow.appendChild(s);
}
}
customElements.define('x-view-media', ViewMedia);