私はプロジェクトのダイアログに取り組んでいて、それをオブジェクトコンストラクターにしました。
function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
this.dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
this.No = this.dialog.getElementsByTagName("button")[0];
this.Yes = this.dialog.getElementsByTagName("button")[1];
var dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle.innerHTML = title;
document.getElementsByClassName("dialogCon")[0].style.display = "flex";
noClicked();
yesClicked();
}
<div class="dialogCon">
<div class="dialog">
<h1></h1>
<button type="button">No</button>
<button type="button">Yes</button>
</div>
</div>
問題は、「this.no」または「this.yes」にアクセスしたいときに、undefinedのプロパティ「No」を読み取れなくなることです。これは、次のコードを使用したときに発生しました。
var d = new createDialog("Sample dialog. Exit?", function() {
console.log(d.No);
}, function() {
console.log(d.Yes);
});
コンストラクター内でnoClicked()とyesClicked()をすぐに呼び出しています。「いいえ」と「はい」をクリックすると、電話をかけたいと思います。これらの関数をボタンのイベントリスナーに追加する必要があります。以下のスニペットをお試しください。
function createDialog(title, noClicked = function(){}, yesClicked = function(){}) {
this.dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle = this.dialog.getElementsByTagName("h1")[0];
this.No = this.dialog.getElementsByTagName("button")[0];
this.Yes = this.dialog.getElementsByTagName("button")[1];
var dialog = document.getElementsByClassName("dialog")[0];
this.dialogTitle.innerHTML = title;
document.getElementsByClassName("dialogCon")[0].style.display = "flex";
this.No.addEventListener('click',noClicked);
this.Yes.addEventListener('click',yesClicked);
}
var d = new createDialog("Sample dialog. Exit?", function() {
console.log(d.No);
}, function() {
console.log(d.Yes);
});
<div class="dialogCon">
<div class="dialog">
<h1></h1>
<button type="button">No</button>
<button type="button">Yes</button>
</div>
</div>
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加