用空格修改CSS名称时出现Javascript InvalidCharacterError [英] Javascript InvalidCharacterError when modifying a css name with a space
问题描述
我正在修改一些通过JavaScript动态生成的按钮。我无法控制静态声明的类名,这就是为什么我编写了一个函数来在页面加载时为我做这件事的原因。我了解为什么会发生这种情况(它不喜欢社交按钮中的空格),我只需要修复即可,而JavaScript绝对不是我的天赋。如果您检查页面上的按钮,则会出现以下错误:
Unncaught InvalidCharacterError:无法在 DOMTokenList上执行 add:提供的令牌( zocial facebook)包含HTML空格字符,在令牌中无效。
这是我的JavaScript代码:
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:
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');
}
如果您想在这里看到它,可以去:
< a href = http://jsbin.com/nifuxoyo/1/watch rel = noreferrer> http://jsbin.com/nifuxoyo/1/watch
If you want to see it live here you go: http://jsbin.com/nifuxoyo/1/watch
推荐答案
好,类名不能包含空格,因为空格分隔多个类名。例如,如果您的HTML包含
Well, class names cannot contain spaces, because the space separates multiple class names from each other. For example, if your HTML contains
class="zocial button"
这意味着该元素具有两个类,即社交和按钮。
it means that this element has two classes, "zocial" and "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');
更多信息可以在 MDN文档。
这篇关于用空格修改CSS名称时出现Javascript InvalidCharacterError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!