将参数/输入数据传递到javascript中的自定义元素 [英] passing parameter/input data to custom elements in javascript
问题描述
我正在尝试实现与此代码相同的代码使用JavaScript,因此将以下代码写为btn.js文件:
I'm trying to implement the same code of this using JavaScript, so wrote the below code as btn.js file:
// Create a new object based of the HTMLElement prototype
var SaveBtn = Object.create(HTMLElement.prototype);
// Set up the element.
SaveBtn.createdCallback = function() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
this.type='button';
// Add an event listener to the image.
this.addEventListener('click', function(e) {
alert('got a click');
document.getElementById("ShowButton").value= "Hide Filter";
});
};
// Register the new element.
var Xbtn =document.registerElement('save-button', {
prototype: SaveBtn,
extends: 'input'
});
并在另一个main.js函数中调用它,如下所示:
and called it in the other function main.js as below:
window.addEventListener("load", onLoad, false);
function onLoad() {
var host = document.querySelector('#host');
var el = new Xbtn();
host.appendChild(el);
}
这很好用,并给了我毯子按钮.
this worked fine, and gave me blanket button.
现在我想将要显示的文本"传递到按钮中,我尝试了以下操作:
now I want to pass the 'text' to be displayed into the button, I tried the below:
在index.html中,我已经:
in the index.html I've:
<div id="host"></div>
<input id="ShowButton" type="button" value="Show Filter"/>
在main.js中:
el.value = 'click me';
以及btn.js:
this.value = this.getAttribute('text');
但失败,并且按钮仍然为空!考虑到单击后其他按钮的值已更改
but failed, and the button still empty! considering that the other button value is changed upon the click
有什么想法吗?
推荐答案
仅在定义的功能范围内可以访问影子DOM根.您要么需要将影子DOM根对象分配给外部作用域变量,要么需要公开操作影子DOM的作用域内函数.由于您要操纵多个元素的影子DOM,因此在每个实例上使用setter函数是最佳选择.
The shadow DOM root is only accessible within the function-scope it is defined. You either need to assign the shadow DOM root object to an outer-scope variable, or you need to expose an in-scope function that manipulates the shadow DOM. Since you want to manipulate the shadow DOM for multiple elements, a setter function on each instance is the best option.
您可以完全公开影子DOM:
You can expose the shadow DOM entirely:
SaveBtn.createdCallback = function() {
var shadow = this.createShadowRoot();
this.myShadow = shadow;
//...
}
...
el.myShadow.textContent = "click me";
但是,由于影子DOM的一个主要功能是能够隐藏DOM组件,使其不受其他脚本的操纵,因此,您可能希望拥有一个setter函数,例如,该函数可以验证输入并在内部执行该操纵:>
However, since a major feature of the shadow DOM is being able to hide DOM components from manipulation by other scripts, you may instead wish to have a setter function that (for example) validates input and performs the manipulation internally:
SaveBtn.createdCallback = function() {
var shadow = this.createShadowRoot();
this.setShadowText = function(text) {
shadow.textContent = text;
}
//...
}
...
el.setShadowText("click me");
这篇关于将参数/输入数据传递到javascript中的自定义元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!