不能将事件绑定到由脚本创建的元素

Can't bind event to element, created by script

本文关键字:脚本 创建 元素 事件 绑定 不能      更新时间:2023-09-26

我正在学习纯JavaScript。目前我正在探索DOM对象,如窗口,文档,元素等…

我在飞行中创建文本字段,并希望将函数绑定到每个元素的事件(例如onfocusonblur),并将self元素作为参数传递(如'this')。

下面的脚本创建文本字段并将其绑定到一个特定的函数。

var txt= document.createElement("input");
txt.type="text";
txt.value='0';
txt.size=12;
txt.style.textAlign="right";
txt.id="txt_"+self.count;
txt.addEventListener('focus', txt_focus(txt));
txt.addEventListener('blur', txt_blur(txt));

下面是函数:

function txt_focus(txt){
txt.value=txt.id;
txt.style.backgroundColor='yellow';
}
function txt_blur(txt){
txt.style.backgroundColor='white';
}

此函数将给定参数识别为元素并将其ID设置为value属性,但不影响背景颜色。我错过了什么?

完整的HTML代码:

<html>
<head>
<script type="text/javascript">
self.count =0;
function txt_focus(txt){
  txt.value=txt.id;
  txt.style.backgroundColor='yellow';
}
function txt_blur(txt){
  txt.style.backgroundColor='white';
}
function removeGroup(){
  if (self.count<1) {return;} 
  var parent=document.getElementById("myDiv");
  var fs_x =document.getElementById('fs_'+self.count);
  parent.removeChild(fs_x);
  self.count--;
}
function addGroup(){
  if (self.count>11) {return;} 
  self.count++;
  var parent=document.getElementById("myDiv");
  var fs=document.createElement("fieldSet");
  fs.style.borderRadius="7px"; 
  fs.style.height="45px";
  fs.id='fs_'+self.count;
  var l=document.createElement("legend");
  l.innerHTML="interval_"+self.count;
  l.style.color="darkgreen";
  l.style.fontStyle="italic";
  fs.appendChild(l);
  var d1= document.createElement("input");
  d1.type="date";
  d1.value='2014-05-01';
  d1.id='d1_'+self.count;
  fs.appendChild(d1);
  var d2= document.createElement("input");
  d2.type="date";
  d2.value='2014-05-22';
  d2.id='d2_'+self.count;
  fs.appendChild(d2);
  var txt= document.createElement("input");
  txt.type="text";
  txt.value='0';
  txt.size=12;
  txt.style.textAlign="right";
  txt.id="txt_"+self.count;
  txt.addEventListener('focus', txt_focus(txt));
  txt.addEventListener('blur', txt_blur(txt));
  fs.appendChild(txt);
  parent.appendChild(fs);
  fs.scrollIntoView();
}
</script>
</head>
<body>
<input type="hidden" id="hd1" value="0"> </input>
<button onclick="addGroup();"> Add a group</button>
<button onclick="removeGroup();"> Remove a group</button>

<div id="myDiv" style="padding:7px;position:relative;margin-top:15px;width:500px;height:500px;background-color:#ccbbcc;overflow-y:auto;border:1px red solid;border-radius:15px;">
</div>
</body>
</html>

解决方案需要纯JavaScript,但JQuery解决方案也很有趣。

第二个问题是:

我有一些基本的JavaScript背景(如数学,字符串,函数,数组,类等),我想要你的建议:是否有必要深入挖掘JavaScript的细节,而不是跳转到JQuery?

这里的问题是引用函数和调用函数之间的区别。当你添加圆括号时,你调用函数并返回结果,默认结果是undefined

在事件处理程序中,您希望仅引用

函数
txt.addEventListener('focus', txt_focus);

如果必须传递参数,则使用匿名函数

txt.addEventListener('focus', function() {
    txt_focus(txt);
});

但是这里没有意义,因为您传递的是元素,您可以在函数内使用this来访问

txt.addEventListener('focus', txt_focus);
function txt_focus() {
    var txt = this; // the element
}