我有这堂课
function user(){
this.create_user = function(){
var $el = document.createElement('div');
$el.classList.add('user');
$el.innerHTML = '<a href="#">I am a user</a>';
document.querySelector('body').appendChild($el);
}
this.sayMyName = function($name){
alert($name);
}
return this.create_user();
}
var user = new user();
现在有一种方法可以在单击新创建的元素时使用方法“ sayMyName”吗?尝试过
function user(){
this.create_user = function(){
var $el = document.createElement('div');
$el.classList.add('user');
$el.innerHTML = '<a href="#" onClick="this.sayMyName("jonas")">I am a user</a>';
document.querySelector('body').appendChild($el);
}
this.sayMyName = function($name){
alert($name);
}
return this.create_user();
}
var user = new user();
但不幸的是没有用,有什么帮助,想法吗?
答案 0 :(得分:1)
请尝试使用bind
function user(){
this.sayMyName = function($name){
alert($name);
}
this.create_user = function(){
var $el = document.createElement('div');
$el.classList.add('user');
$el.innerHTML = '<a href="#" >I am a user</a>';
var link = ( $el.firstElementChild || $el.firstChild );
link.addEventListener('click', this.sayMyName.bind(this, 'jonas') );
document.querySelector('body').appendChild($el);
}
return this.create_user();
}
答案 1 :(得分:-1)
编辑:更合适的JavaScript尝试(如评论所述)将是这样添加一个Listener:
$el.addEventListener('click', function() {
//
});
// OR
$el.addEventListener('click', this.sayMyName());
就个人而言,我对这些侦听器无法正常工作有疑问。如果发生这种情况,请确保将以下代码放在其中:
document.addEventListener('DOMContentLoaded', function() {
//
});