JS 自定义元素,如何获取属性值
JS Custom Elements, how I can get attribute value
我只是在学习,所以我决定重复已经存在的标签,所以
我有自定义元素 custom-select,他必须做与 select 相同的事情,但我需要获取属性值
的值
这是我的自定义元素代码
class CustomSelect extends HTMLElement{
static get observedAttributes(){
return ["value"]
}
attributesChangeCallback(name,val){
console.log("1234")
if(name === "value"){
this.addTxt(val)
}
}
connectedCallback(){
this.innerHTML = `
<div class = "first" id = "divId"></div>
<div id = "spisoc">
</div>
`
let elem = document.getElementById('divId')
let elem2 = document.getElementById('spisoc')
elem.onclick = function(){
elem2.classList.add("spisocDesing")
}
function addTxt(val){
elem2.innerHTML += val
}
}
}
customElements.define('custom-select',CustomSelect)
这是 html inside body
<body>
<custom-select id = "elem" value = "1234">
</custom-select>
<script>
</script>
</body>
</html>
您可以按照以下脚本自定义元素
<some-element cutom-elem /> <other-element custom-elem />
<script>
var customs = document.querySelectorAll( "*[custom-elem]" )
</script>
<style>
*[custom-elem] { display: block ; }
</style>
我只是在学习,所以我决定重复已经存在的标签,所以
我有自定义元素 custom-select,他必须做与 select 相同的事情,但我需要获取属性值
的值这是我的自定义元素代码
class CustomSelect extends HTMLElement{
static get observedAttributes(){
return ["value"]
}
attributesChangeCallback(name,val){
console.log("1234")
if(name === "value"){
this.addTxt(val)
}
}
connectedCallback(){
this.innerHTML = `
<div class = "first" id = "divId"></div>
<div id = "spisoc">
</div>
`
let elem = document.getElementById('divId')
let elem2 = document.getElementById('spisoc')
elem.onclick = function(){
elem2.classList.add("spisocDesing")
}
function addTxt(val){
elem2.innerHTML += val
}
}
}
customElements.define('custom-select',CustomSelect)
这是 html inside body
<body>
<custom-select id = "elem" value = "1234">
</custom-select>
<script>
</script>
</body>
</html>
您可以按照以下脚本自定义元素
<some-element cutom-elem /> <other-element custom-elem />
<script>
var customs = document.querySelectorAll( "*[custom-elem]" )
</script>
<style>
*[custom-elem] { display: block ; }
</style>