关键事件不适用于多个ckeditors

我有这个jsfiddle在这里,当用户在ckeditor上输入时,会向用户提醒过滤词。在我的例子中,过滤后的单词are ants and words 。所以如果你输入这些单词,它会提醒用户。

HTML

  

JS

 var filter = ['ants', 'words'], // our list of words regAry = new Array(), // we'll create one regex per word for testing alertedWords = new Array(), // keep track of how many words there were at the last alert, for each word reg = new RegExp("(/s" + filter.join("|") + "/s)", "g"); // one regex to rule them all! for(var f in filter) { // setup... regAry[f] = new RegExp(filter[f], "g"); // one regex per word for testing alertedWords[f] = 0; // no alerts yet, so 0 for each word } var editor = CKEDITOR.replace( 'editor1' ); //var value = CKEDITOR.instances['editor1'].getData(); //alert(value); editor.on('contentDom', function() { editor.document.on('keyup', function(event) { for(var index in regAry) { // loop over our list of words var value = CKEDITOR.instances['editor1'].getData(); var test = value.match(regAry[index]); // test how many times this word appears if( test && test.length > alertedWords[index] ) // if it appears more than the last time we alerted... { alert("The following word/words "+ CKEDITOR.instances['editor1'].getData().match(regAry[index])+" is banned"); // do an alert! } alertedWords[index] = (test ? test.length : 0); // update the word count for this word } // keep looping }); }); 

现在我的问题出现了,如果我有2个或更多像这样的 ckeditor它似乎没有工作。尽管编辑出现但警报不会出现。

HTML

   

JS

 var filter = ['ants', 'words'], // our list of words regAry = new Array(), // we'll create one regex per word for testing alertedWords = new Array(), // keep track of how many words there were at the last alert, for each word reg = new RegExp("(/s" + filter.join("|") + "/s)", "g"); // one regex to rule them all! for(var f in filter) { // setup... regAry[f] = new RegExp(filter[f], "g"); // one regex per word for testing alertedWords[f] = 0; // no alerts yet, so 0 for each word } for(var i=1;i alertedWords[index] ) // if it appears more than the last time we alerted... { alert("The following word/words "+ CKEDITOR.instances['editor'+i].getData().match(regAry[index])+" is banned"); // do an alert! } alertedWords[index] = (test ? test.length : 0); // update the word count for this word } // keep looping }); }); } 

该怎么办?

你的问题与i价值有关。 当触发事件( contentDomkeyup )时, i3 。 因此,听众正在尝试使用CKEDITOR.instance("editor3") ,它根本不存在。 解决方案是,通过单独的函数添加侦听器,它接受i作为参数:

 for(var i=1; i<3; i++){ addListeners(i); } function addListeners(i){ //body of for loop } 

DEMO

不要使用for循环,但each使用jquery,如:

 $( 'input[type=textarea]').each( function(indx) { var editor = CKEDITOR.replace( $(this).attr('id') ); ..... 

小提琴