我正在使用 javascript 和 jquery 处理 Goolge Apis
问题是某些 YouTube channel 的标题有“空格”或!或 ... 符号
所以我需要将这些标题作为字符串传递,但即使那样我也会出错
错误:语法错误,无法识别的表达式:#channelBomB!
我的代码在下面
function placeChannelVideoIds(YouTubeChannelTitle){
$('#channel'+String(YouTubeChannelTitle)).append('\
<H1>YouTubeChannelTitle</H1>>);
}
placeChannelVideoIds(String(YouTubeChannelTitle));
最佳答案
这与您尝试附加的字符串无关,它是 id 不能有任何空格、标记或 !
,基本上,您只能使用 a-zA-Z
, 0-9
, _-.
id
in HTML 4For HTML 4, ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
id
in HTML 5HTML 5 accept '_', '-' and '.' if not at the beginning fo the id. It is also a true global attribute.
id attribute's value must not contain whitespace (spaces, tabs etc.). Browsers treat non-conforming IDs that contain whitespace as if the whitespace is part of the ID. In contrast to the class attribute, which allows space-separated values, elements can only have one single ID.
REF: https://developer.mozilla.org/en/docs/Web/HTML/Global_attributes/id
解决方案:
好的,所以你不能在 id 中使用任何字符串,但是你可以对字符串进行哈希处理以获得唯一的数字并用作 id,并且你对相同的字符串进行哈希处理你总是得到相同的唯一 id.
然后您的代码将如下所示(将 sdbmCode
函数添加到您的代码中):
function placeChannelVideoIds(YouTubeChannelTitle){
var hash_id = sdbmCode(YouTubeChannelTitle);
$('#channel'+ hash_id).append('<h1>'+YouTubeChannelTitle+'</h1>');
}
placeChannelVideoIds(YouTubeChannelTitle);
正如您在下面的代码示例中所看到的,任何字符串都可以散列为一个唯一的 ID(好吧,您很少会从两个不同的字符串中获得相同的 ID(例如连续 3 次中奖彩票) )).
REF: http://erlycoder.com/49/javascript-hash-functions-to-convert-string-into-integer-hash-
sdbmCode = function(str){
var hash = 0;
for (i = 0; i < str.length; i++) {
char = str.charCodeAt(i);
hash = char + (hash << 6) + (hash << 16) - hash;
}
return Math.abs(hash);
}
var str1 = 'BomB!';
var str2 = 'Bo mB!';
var str3 = '!!$%#^^@';
var str4 = 'test!!$%#^^@';
var str5 = 'test!!$%#^^@!';
var str6 = '"test!!$%#^^@"';
console.log('hash '+str1+' -->'+sdbmCode(str1));
console.log('hash '+str1+' -->'+sdbmCode(str1));
console.log('hash '+str2+' -->'+sdbmCode(str2));
console.log('hash '+str3+' -->'+sdbmCode(str3));
console.log('hash '+str4+' -->'+sdbmCode(str4));
console.log('hash '+str5+' -->'+sdbmCode(str5));
console.log('hash '+str6+' -->'+sdbmCode(str6));
关于javascript - 传递字符串! ,' ' ... 符号到 jquery append,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44275537/