我正在使用javascript和jquery与Goolge Apis合作

问题是某些YouTube频道的标题带有“ SPACE”或!或...符号

所以我需要将那些Titles作为字符串传递,但是即使这样我也会出错

Error: Syntax error, unrecognized expression: #channelBomB!

我的代码如下

function placeChannelVideoIds(YouTubeChannelTitle){

    $('#channel'+String(YouTubeChannelTitle)).append('\
        <H1>YouTubeChannelTitle</H1>>);

}
placeChannelVideoIds(String(YouTubeChannelTitle));

最佳答案

这与您要附加的字符串无关,它是id不能包含任何空格,标记或!,基本上,您只能使用a-zA-Z0-9_-.


  HTML 4中的id
  
  对于HTML 4,ID和NAME令牌必须以字母([A-Za-z])开头,后可以跟任意数量的字母,数字([0-9]),连字符(“-”),下划线( “ _”),冒号(“:”)和句点(“。”)。
  
  HTML 5中的id
  
  HTML 5接受'_','-'和'。'如果不是开头的ID。这也是一个真正的全局属性。
  
  id属性的值不能包含空格(空格,制表符等)。浏览器将包含空格的不合格ID视为空白,将其视为ID的一部分。与允许使用空格分隔值的class属性相反,元素只能具有一个ID。
  
  参考: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次中奖)。


  参考: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附加中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44275537/

10-12 16:27
查看更多