使用空格修改 css 名称时出现 Javascript InvalidCharacterError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22133722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 22:31:19  来源:igfitidea点击:

Javascript InvalidCharacterError when modifying a css name with a space

javascriptcssdom

提问by DigitalRayne

I'm modifying some buttons that are dynamically generated through JavaScript. I have no control over statically declaring the class names which is why I've written a function to do it for me on page load. I understand why it's happening (it doesn't like the space in 'zocial button'), I just need a fix and I'm definitely not that gifted with JavaScript. Here's the error if you inspect the button on the page: Unncaught InvalidCharacterError: Failed to execute 'add' on 'DOMTokenList': The token provided ('zocial facebook') contains HTML space characters, which are not valid in tokens. Here's my javascript code:

我正在修改一些通过 JavaScript 动态生成的按钮。我无法控制静态声明类名,这就是为什么我编写了一个函数来在页面加载时为我做这件事。我明白为什么会发生这种情况(它不喜欢“zocial 按钮”中的空格),我只需要修复,而且我绝对没有 JavaScript 天赋。如果您检查页面上的按钮,则会出现以下错误: Unncaught InvalidCharacterError: Failed to execute 'add' on 'DOMTokenList': The token provided ('zocial facebook') contains HTML space characters, which is not valid in tokens. 这是我的 javascript 代码:

var buttonz = document.getElementsByName('provider');
for (var i = 0, length = buttonz.length; i < length; i++) {
    if (buttonz[i].value == 'Facebook')
    {
        buttonz[i].classList.remove('btn-default');
        buttonz[i].classList.add('zocial button');
    }

If you want to see it live here you go: http://jsbin.com/nifuxoyo/1/watch

如果你想在这里看到它,你去:http: //jsbin.com/nifuxoyo/1/watch

回答by Felix Kling

Well, class names cannot contain spaces, because the space separatesmultiple class names from each other. For example, if your HTML contains

好吧,类名不能包含空格,因为空格多个类名彼此分开。例如,如果您的 HTML 包含

class="zocial button"

it means that this element has twoclasses, "zocial" and "button".

这意味着这个元素有两个类,“zocial”和“button”。

If you want to add both of these classes, you have to pass each one as argument to the method:

如果要添加这两个类,则必须将每个类都作为参数传递给该方法:

buttonz[i].classList.add('zocial', 'button');

More information can be found in the MDN documentation.

更多信息可以在MDN 文档中找到。