我有这个代码:
var button = $(event.target);
var videoElement = button.parents(".video-row").find("iframe");
src = videoElement.attr("src");
title = videoElement.attr("title");
description = videoElement.attr("description");
...
button.classList.add("green-button"); //error here
这给出了这个错误:
Uncaught TypeError: Cannot read property 'add' of undefined
button
变量似乎有问题。我该如何修复它?
最佳答案
您正在使用 jQuery ($
) 定义 button
,但随后调用 .classList
,就好像 button
是一个原生 DOM 元素。其实不是,它是 jQuery 的一个实例。您需要使用 .addClass()
jQuery 方法:
button.addClass("green-button");
或者,如果您想使用.classList
,您可以执行以下操作:
button[0].classList.add('green-button')
[0]
从 jQuery 实例获取实际的 DOM 元素。
关于javascript - 未捕获的 TypeError : Cannot read property 'add' of undefined: event. 目标变量将类添加到类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60843271/