我目前正在将按钮上的 ID 传递给一个函数。 我想在 jQuery 表中从使用按钮切换到使用 td(一旦我学会了如何这样做)。 我想更改为使用一个类,因为我想让一行中的每个 td 都可点击。 一行中的每个 td 都会将完全相同的变量传递给函数。
所以一行中的每个 td 将执行与按钮完全相同的操作。 意思是我想让 td 可点击并调用该函数。 所有 td 都将具有相同的 id(清楚 - 在上面的示例中),我读到多次使用相同的 id 是不好的做法,并且稍后可能会在我的 jQuery 代码中出现问题。我确实读到过多次使用一个类是可以的,因此尝试进行更改。
例如一个按钮设置如下:
<input type="button" id="clear" style="width:110px;" onclick="return SetShift(this.id)" value="Clear" />
SetShift 函数是:
function SetShift(id) {
// Gets/passes the workday shift to/from the localStorage.
const targetStateValue = localStorage.getItem('shiftstatus');
if (targetStateValue === null) {
localStorage.setItem('shiftstatus', id);
} else {
localStorage.setItem('shiftstatus', id);
}
}
我试图将 id 更改为类,但出现以下错误:
Uncaught SyntaxError: Unexpected token class
Uncaught ReferenceError: SetShift is not defined
at HTMLInputElement.onclick ((index):36)
最佳答案
如评论中所述,class
是 JavaSript 中的保留名称(参见 this)
你可以做的是:
function SetShift(evt) {
console.log('className', evt.target.className);
}
<button class="clear" onclick="SetShift(event)">
Click me
</button>
请注意,如果您有多个类,则需要使用 classList.contains
关于javascript - 是否可以将类传递给 Javascript 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57532448/