2014-10-30 3 views
1

jquery로 다채로운 텍스트 영역을 만들려고합니다. 잘 작동하지만 입력 버튼을 누르면 색상이 변경되지 않습니다. 여기 내 코드입니다.Jquery는 입력 버튼을 누른 후 텍스트 색상을 변경하지 않습니다.

<html> 
<script type="text/javascript" src="jquery/jquery-1.6.2.js"></script> 
<script type="text/javascript"> 
//<![CDATA[ 

//declearing of array of collored words 
var style = []; 
var words = ['function','var','editableText']; 
style['function'] = 'color:#772AC3;'; 
style['var'] = 'color:red;'; 
style['editableText'] = 'color:#2A00FF;'; 

//function for coloring words 
function ColorDiv(words,color,id) 
{ 
for (var index = 0; index < words.length; ++index) { 
$("#"+id+":contains("+words[index]+")").each(function() { 
    $(this).html($(this).html().replace(words[index], "<span class='red' style='"+color[words[index]]+"'>"+words[index]+"</span>")); 
}); 
} 
} 

//start up functions definations 
$(window).load(function(){ 
ColorDiv(words,color,'fool'); 

});//]]> 


</script> 
<textarea id="fool_txt"></textarea> 
<div id="fool"></div> 

<script> 
$("#fool_txt") 
.keyup(function() { 
var value = $(this).val(); 
$("#fool").text(value); 
ColorDiv(words,style,'fool'); 
}) 
.keyup(); 

</script> 

나는 이것을 해결하는 방법을 모른다.

ColorDiv(words,color,'fool'); 

이이 기능의 다른 호출에 전달로 스타일 있어야된다 처음 ColorDiv 함수를 호출 할 때

+0

이벤트를 입력 확인하기 위해 확인하실 수 있습니다 (e.keyCode의 == 13) 알림 ("enter"); }); – bumbumpaw

+0

아무 경고가 없습니다 –

답변

1

귀하의 논리가 수정되었습니다. 당신이 $ (문서) CSTE 연구진 ('의 keyup', '#의 fool_txt', 기능 (전자) { 경우 시도, this fiddle

var style = []; 
var words = ['function', 'var', 'editableText']; 
style['function'] = 'color:#772AC3;'; 
style['var'] = 'color:red;'; 
style['editableText'] = 'color:#2A00FF;'; 

//function for coloring words 
function ColorDiv(words, color, arr, id) { 
    for (var i = 0; i < arr.length; i++) { 
     arr[i] = arr[i].replace(/[\n\r]/g,"<br/>"); 
     var matchedIndex = words.indexOf(arr[i]); 
     if (matchedIndex !== -1) { 
      arr[i] = "<span class='red' style='" + color[words[matchedIndex]] + "'>" + arr[i] + "</span>"; 
     } 
    } 
    $("#" + id).html(arr.join(" ")); 
} 

//start up functions definations 
$(window).load(function() {//TODO: modify this to document ready and below fn param 
    ColorDiv(words, color, 'fool'); 

}); 

$("#fool_txt") 
    .keyup(function() {//TODO: can be optimized by selective invoking ColorDiv 
    var value = $(this).val(); 
    ColorDiv(words, style, value.split(new RegExp("\\b")), 'fool'); 
}) 
+0

잘 작동합니다.'textarea'에서'enter'를 누르면 div에'
'을 넣을 수있는 방법이 있습니까? –

+0

안녕하세요. arr [i] = arr [i] .replace (/ [\ n \ r]/g, "
"); 일치 색인 앞에 나는 바이올린을 업데이트했다. – Amitesh

0

당신은 정의되지 않은 변수 색상를 사용하고 계십니까?

나는 당신이 내가 눈에 거슬리지을 유지하기 위해 별도의 파일에 모든 JS 이동 한 바이올린에 http://jsfiddle.net/ux3yph9j/ 에 원하는 것을 믿는 바이올린을 만들었습니다.

코드는 $ (window) .load() 대신 $ (document) .ready()를 사용하는 경우에만 작동합니다. 제 생각에 이것은 바이올린에있는 것 같습니다.

+0

어떻게 작동합니까? 어떻게 테스트합니까? 어떤 색상도 볼 수 없습니다. –

+0

선택한 단어 (function, var, editableText) 중 하나를 결과 창의 텍스트 상자에 입력하면 단어 입력이 끝나면 색상이 변경됩니다. –

관련 문제