Javascript 如何在自定义元素中包装输入字段?
我试图将输入字段包装在自定义元素中 自定义元素DOM如下所示:Javascript 如何在自定义元素中包装输入字段?,javascript,html,custom-element,Javascript,Html,Custom Element,我试图将输入字段包装在自定义元素中 自定义元素DOM如下所示: <custom-element> <div class="fancy-wrapper"> <input value="4"> </div> <custom-element> <custom-input id="test"></custom-input> <script> let test = document.get
<custom-element>
<div class="fancy-wrapper">
<input value="4">
</div>
<custom-element>
<custom-input id="test"></custom-input>
<script>
let test = document.getElementById('test')
console.log(test.value); // should return 4 (value of inner input)
test.onkeydown = function(e){
console.log(e.target.value); // should the new value of the inner input
};
</script>
而元素的工作方式应如下所示:
<custom-element>
<div class="fancy-wrapper">
<input value="4">
</div>
<custom-element>
<custom-input id="test"></custom-input>
<script>
let test = document.getElementById('test')
console.log(test.value); // should return 4 (value of inner input)
test.onkeydown = function(e){
console.log(e.target.value); // should the new value of the inner input
};
</script>
让test=document.getElementById('test'))
console.log(test.value);//应返回4(内部输入值)
test.onkeydown=功能(e){
console.log(e.target.value);//应该输入内部输入的新值吗
};
有没有办法将
属性重定向到其中的
属性,而不必手动连接所有内容?您可以附加到自定义元素标记的innerHTML中
var string=“如果我理解了您的问题,您希望将自定义元素
的所有属性复制到输入
标记
你能做的是
//get all attributes of custom element
var el = document.getElementById ('test');
// get all attributes
var attrs = el.getAttributeNames(); // returns an array
// loop over attrs array and append the attribute and value in the input,
// I am assuming, you will not add copy id attribute here.
var input = el.getElementsByTagName ('input')[0];
for (var index = 0; index < attrs.length; index++) {
if (attrs[index] !== 'id') {
// set attribute of input with attribute name from the array,
// and get the value from from input.
input.setAttribute (attrs[index], el.getAttribute (attrs[index]));
}
}
//获取自定义元素的所有属性
var el=document.getElementById('test');
//获取所有属性
var attrs=el.getAttributeNames();//返回一个数组
//循环attrs数组并在输入中附加属性和值,
//我假设,您不会在这里添加复制id属性。
var input=el.getElementsByTagName('input')[0];
对于(变量索引=0;索引
这是一个想法,你可以做其他事情。HTML:
<custom-element id="test">
<div><input value="43" /></div>
</custom-element>
可以看一看不,它与拥有一个DIV和另一个子DIV没有什么不同
您必须自己建立CustomElement和内容之间的连接
一种方法是在自定义元素上定义获取子输入值的Get/Set函数
当然,您不必手动声明Get/Set,而是可以循环任何子元素,并使用或在CustomElement上赋值
下面的示例创建了2个输入字段和一个this.INPUT
数组:
<number-and-range>
<input type="number"> // this.input[0]
<input type="range"> // this.input[1]
</number-and-range>
自定义元素:连接的输入和范围滑块
请输入一个介于20和50之间的数字,或使用范围滑块
我编辑了这个问题,让它更清楚我想做什么。我的问题不是给自定义元素分配一个元素,我基本上想要一个自定义HTMLInputElement,而是在实际输入周围有其他元素。我知道如何创建自定义元素,问题是如何在输入周围创建一个包装器放置元素,而不失去对它的直接访问权。问题不清楚。抱歉。根据问题@Daveman重构