我有一个遍历数组,以便将文本放置在网页上的单独div中(此后为div设置动画)。我想向每个div添加一个onclick,因此当单击div / text时,字体粗细会发生变化。我知道至少有一种在更简单的情况下使用onclick的方法:
<div class="nameDiv" id="div1" onclick='boldText(this, this.id);'>Test</div>
<script>
function boldText(txt, txtid){
var el = document.getElementById(txtid);
var fontstyle = window.getComputedStyle(el, null).fontWeight;
if (fontstyle != '800') {
txt.style.fontWeight = '800';
} else {
txt.style.fontWeight = '300';
}
}
</script>
但是,我无法通过迭代在代码中使用相同类型的东西。
var setNames = function() {
var h = 0;
for(var n = 0; n < numberStudents; n++){
var divName = "floatName" + n;
var names = nameArray[n].fields.nickname; <!-- gets the text/name for each div -->
var divTag = document.createElement('div');
divTag.id = divName;
divTag.innerHTML = names;
divTag.className = "randomFloat";
// try to give each div an onclick
divTag.onclick = boldText(this, this.id);
studentCol.appendChild(divTag); <!-- attach to studentCol/'anchor'/parent element -->
};
};
setNames();
function boldText(txt, txtid){ <!-- pass both the object and the object id -->
var el = document.getElementById(txtid);
// I've tried both lines below -->
var fontstyle = window.getComputedStyle(el, null).fontWeight; <!-- gives me an error saying el is not an object -->
//var fontstyle = window.getComputedStyle(el, null).fontWeight;
// line above gives TypeError: Argument 1 of Window.getComputedStyle does not implement interface Element -->
if (fontstyle != '300') {
txt.style.fontWeight = '300';
} else {
txt.style.fontWeight = '800';
}
};
每个divTag.id是否有可能具有单独的onclick?如果是这样,我需要更改我的代码吗?
答案 0 :(得分:2)
问题是您要分配boldText
函数结果,而不是函数本身。请尝试以下方法:
divTag.onclick = boldText;
通过这种方式,您可以访问this
函数中的boldText
,而无需向其传递任何参数。例如
this.style.fontWeight = '300';