我想创建一个可以在html中调用的常用函数,这样我就可以从变量中更新值。
function getActivityPoint(activityName) {
document.getElementsByClassName('share_points')[0].innerHTML = activityName;
}
我的变量
var ap = {
'movie_review':'20',
}
在HTML中,我想这样做。
<div class="share_points" onload="getActivityPoint(ap.movie_review)">-</div>
<div class="share_points" onload="getActivityPoint(ap.game_review)">-</div>
.............
答案 0 :(得分:2)
内联 onload 事件不适用于div。
您可以使用数据属性更改代码以更改div,例如:
<div class="share_points" data-load="movie_review">-</div>
并在窗口加载,您可以开展工作:
window.addEventListener("load", function(event) {
document.querySelectorAll('.share_points').forEach(ele => getActivityPoint(ele, ap[ele.dataset.load]));
});
function getActivityPoint(ele, activityName) {
ele.textContent = activityName;
}
var ap = {
'movie_review':'20',
'game_review': 10
}
/****************
For Compatibility issue you may write:
window.addEventListener("load", function (event) {
Array.prototype.slice.call(document.querySelectorAll('.share_points')).forEach(function (ele) {
getActivityPoint(ele, ap[ele.dataset.load]);
});
});
For IE < 9 the solution is:
window.addEventListener("load", function (event) {
var divs = document.querySelectorAll('.share_points');
for (i = 0; i < divs.length; i++) {
getActivityPoint(divs[i], ap[divs[i].dataset.load]);
}
});
*/
<div class="share_points" data-load="movie_review">-</div>
<div class="share_points" data-load="game_review">-</div>
答案 1 :(得分:1)
你可以这样做:
var ap = {
'movie_review': '20',
'game_review': '100'
},
share_points = document.getElementsByClassName('share_points');
window.addEventListener('load', function() {
Array.prototype.forEach.call(share_points, function(el) {
el.innerHTML = ap[el.dataset.review];
});
});
<div class="share_points" data-review="movie_review">-</div>
<div class="share_points" data-review="game_review">-</div>