所以我有一个函数将字符串值赋给div。我想知道当我调用该函数时,如何将内容特定于特定Div?显然我可以做整个[0],[1],[2]等等,但这样做会破坏使用户友好的目的。我意识到For循环在这里用class属性赋予所有div。
HTML
<div id="property">
<p>Properties</p>
<div class="properties" onclick="AddProperty('house# 35C', '3-4', '$50')"></div>
<div class="properties" onclick="AddProperty('house# 22F', '7-8', '$75')"></div>
<div class="properties" onclick="AddProperty('house# 19D', '9-10', '$100')"></div>
</div>
的JavaScript
function AddProperty(propnum, sleepdays, rent) {
var myProperties =document.getElementsByClassName("properties");
for (var i=0; i<myProperties.length; i++) {
myProperties[i].style.backgroundColor = "red";
myProperties[i].innerHTML = new Array(propnum, sleepdays, rent)
}
}
答案 0 :(得分:0)
如果你只是想添加一个id,你可以使用像这样::
的element.idfunction AddProperty(propnum, sleepdays, rent) {
var myProperties =document.getElementsByClassName("properties");
for (var i=0; i<myProperties.length; i++) {
myProperties[i].style.backgroundColor = "red";
myProperties[i].innerHTML = new Array(propnum, sleepdays, rent)
myProperties[i].id = i+1;
}
}
答案 1 :(得分:0)
如果我理解正确,你应该使用“this”:
<div class="properties" onclick="AddProperty(this, 'house# 35C', '3-4', '$50')">1</div>
和js将是
window.AddProperty = function(el, propnum, sleepdays, rent) {
el.style.backgroundColor = "red";
el.innerHTML = new Array(propnum, sleepdays, rent)
}