如何将javascript从ID更改为Class?我试着自己做但没有运气,这就是我最终的结果。原始代码用于显示或隐藏元素并记住用户选择。
HTML:
<div class="popup" style="display:none">
<img src="image-url.jpg" alt="alt text" title="title text">
</div>
JAVASCRIPT:
function setCookie (name, value, expires, path, domain, secure) {
document.cookie = name + "=" + escape(value) +
((expires) ? "; expires=" + expires : "") +
((path) ? "; path=" + path : "") +
((domain) ? "; domain=" + domain : "") +
((secure) ? "; secure" : "");
}
function getCookie (name) {
var cookie = " " + document.cookie;
var search = " " + name + "=";
var setStr = null;
var offset = 0;
var end = 0;
if (cookie.length > 0) {
offset = cookie.indexOf(search);
if (offset != -1) {
offset += search.length;
end = cookie.indexOf(";", offset);
if (end == -1) {
end = cookie.length;
}
setStr = unescape(cookie.substring(offset, end));
}
}
if (setStr == 'false') {
setStr = false;
}
if (setStr == 'true') {
setStr = true;
}
if (setStr == 'null') {
setStr = null;
}
return(setStr);
}
function hidePopup() {
setCookie('popup_state', false);
document.getElementsByClassName('popup').style.display = 'none';
}
function showPopup() {
setCookie('popup_state', null);
document.getElementsByClassName('popup').style.display = 'block';
}
function checkPopup() {
if (getCookie('popup_state') == null) {
// if popup was not closed
document.getElementsByClassName('popup').style.display = 'block';
}
}
答案 0 :(得分:0)
document.getElementsByClassName
会返回一个NodeList。并且NodeList没有一个有用的style
属性......它只有length
,并且列表中的每个节点都有索引。
为了设置找到的每个popup
的样式,您应该遍历NodeList。例如:
function showPopups() {
setCookie('popup_state', null);
var popups = document.getElementsByClassName('popup');
for (var i = popups.length - 1; i >= 0; --i) {
popups[i].style.display = '';
}
}
当然,要隐藏它们,您需要将display
设置为none
。
如果你知道你只有一个要改变的元素,(1)为什么你不使用ID? :)但是(2)你可以说document.getElementsByClassName('popup')[0]
来访问一个元素。请注意,但是......如果你有多个,那么你只会改变第一个。