[英]How to call component on click of button in javaScript
我想在javaScript中創建一個組件,單擊按鈕即可調用該組件。
借助於此( https://ayushgp.github.io/html-web-components-using-vanilla-js-part-3/ ),我能夠創建組件,但是在頁面本身加載時會調用此組件。
我想在javaScript中單擊按鈕時調用組件。 提前致謝。
從您提供的鏈接中,我相信這是您正在運行的代碼。
<html>
<head>
<title>Web Component</title>
</head>
<body>
<input type="text" onchange="updateName(this)" placeholder="Name">
<input type="text" onchange="updateAddress(this)" placeholder="Address">
<input type="checkbox" onchange="toggleAdminStatus(this)" placeholder="Name">
<user-card username="Ayush" address="Indore, India" is-admin></user-card>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.14/webcomponents-hi.js"></script>
<script src="/UserCard/UserCard.js"></script>
<script>
function updateAddress(elem) {
document.querySelector('user-card').setAttribute('address', elem.value);
}
function updateName(elem) {
document.querySelector('user-card').setAttribute('username', elem.value);
}
function toggleAdminStatus(elem) {
document.querySelector('user-card').setAttribute('is-admin', elem.checked);
}
</script>
</body>
</html>
<user-card .... ></user-card>
部分在頁面中創建組件,因為user-card
已注冊為自定義元素,並且該元素在頁面加載后立即呈現。
如果要通過單擊按鈕來創建此卡,則需要從主體中刪除user-card
,將onClik偵聽器注冊到將在文檔主體中插入user-card
元素的按鈕上。
樣例代碼:
<html>
<head>
<title>Web Component</title>
</head>
<body>
<input type="text" onchange="updateName(this)" placeholder="Name">
<input type="text" onchange="updateAddress(this)" placeholder="Address">
<input type="checkbox" onchange="toggleAdminStatus(this)" placeholder="Name">
<button onClick="loadCard()">LOAD THE CARD</button>
<div id="card_holder"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/webcomponentsjs/1.0.14/webcomponents-hi.js"></script>
<script src="/UserCard/UserCard.js"></script>
<script>
function loadCard(){
document.getElementById('card-holder').innerHTML = '<user-card username="Ayush" address="Indore, India" is-admin></user-card>';
}
function updateAddress(elem) {
document.querySelector('user-card').setAttribute('address', elem.value);
}
function updateName(elem) {
document.querySelector('user-card').setAttribute('username', elem.value);
}
function toggleAdminStatus(elem) {
document.querySelector('user-card').setAttribute('is-admin', elem.checked);
}
</script>
</body>
</html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.