2015-01-20 1 views
0

자바 스크립트를 사용하여 하나의 파일을 업로드했습니다. 텍스트 파일의 일부를 클릭 가능하게 강조 표시하고 싶습니다. 예 : 업로드 된 파일의 모든 "안녕하세요"를 클릭 가능하게 강조 표시하고 싶습니다.업로드 된 텍스트 파일의 일부분을 클릭하여 자바 스크립트를 사용하여 만듭니다.

버튼 태그를 사용하고 CSS의 배경 및 테두리 속성을 변경했기 때문에 텍스트를 강조 표시 할 수 있지만 버튼을 클릭하면 onclick 동작을 수행 할 수 없습니다.

var sel_data=$("#sel").text(); // for taking the text file in avariable 

var str='hello'; 

//making the regular expression of str 
var re = new RegExp(str,"g"); 

//For replacing the 'str' by highlighted and clickable 'str' 
var re_str="<button class='highlight' id='ty' onclick='alertfunc()' value="+str+">"+str+"</button>" 

//replacement of 'str' by highlighted and clickable 'str' 
var rep_data=sel_data.replace(re,re_str); 
sel_data=rep_data; 

//function to be executed when the button will get clicked 
function alertfunc() { 
    alert('yellow'); 
} 

나는이

var str='hello' 


var re_str="<button class='highlight' id='ty' value="+str+">"+str+"</button>" 

$(".highlight").click(function(){ 
    alert("yellow"); 
}) 

처럼 또는 그들 중 누구도 작동하지 않습니다이

var button = document.getElementById("ty"); 
button.onclick = function(){ 
alert("yellow"); 
} 

그러나처럼 그것을 시도, 을 제안하십시오 :

나는 이런 식으로 시도 위의 예를이 링크로 언급했습니다. Html make text clickable without making it a hyperlink

+0

어떻게 "텍스트 파일"을 출력합니까? 're_str' 변수로 무엇을합니까? 한 단어의 단어를 버튼으로 대체하려는 부분은 어디입니까? 귀하의 질문이 불완전하거나 명확하지 않습니다. – Brewal

+0

내가 언급 한 모든 것을 편집하고 정리했습니다. – Learner

답변

1

여기 몇 가지 잘못된 점이 있습니다. 는 DOM의 실제 HTML 업데이트, 그리고

$(document).ready(function(){ 
    // code 
}); 

:
첫째, 준비 문서에이 코드를 실행

//replacement of 'str' by highlighted and clickable 'str' 
var rep_data=sel_data.replace(re,re_str); 
sel_data=rep_data; 
$("#sel").html(sel_data); // here 

을 그리고 클릭에 대한 이벤트 위임을 사용 :

$("#sel").on('click', '.highlight', function(){ 
    alert("yellow"); 
}); 

demo

+0

고마워요! 원활하게 작동했습니다. – Learner

+0

좋아요! 그럼 대답을 받아 들일 수 있습니다;) – Brewal

0

이것은 jQuery 라이브러리와 ready snippet : contains를 사용하여 수행됩니다.

jQuery.fn.highlight = function (str, className) { 
    var regex = new RegExp(str, "gi"); 
    return this.each(function() { 
     $(this).contents().filter(function() { 
      return this.nodeType == 3 && regex.test(this.nodeValue); 
     }).replaceWith(function() { 
      return (this.nodeValue || "").replace(regex, function(match) { 
       return "<span class=\"" + className + "\">" + match + "</span>"; 
      }); 

     }); 
    }); 
}; 

단어 "안녕하세요"당신의 선택의 클래스와 스팬 감싸 할을 이끌 것이 코드를 사용 : 여기 당신이 필요로하는 코드입니다.

$(".testHighlight *").highlight("hello", "highlight"); 

당신이 설정에 뭔가처럼하는 CSS와 .testHighlight 클래스가 당연히 :

.testHighlight { 
    background:yellow; 
} 

그들을 클릭하려면를 지금

은 당신이 할 필요가있다이 함수를 호출합니다 jQuery로 쉽게 할 수 있습니다 :

$(.testHighlight).click(function(){ 
//YOUR CODE HERE 
}); 

이 스 니펫에 대한 자세한 내용은에서 확인할 수 있습니다..

+0

나는 당신이 기능은 텍스트를 강조 표시하는 데 사용되지만 버튼 태그를 사용하여 달성했다고 믿습니다. 주요 문제는 해당 버튼을 클릭 할 때 클릭 작업을 수행하는 방법입니다. – Learner

+0

답변을 편집했습니다. – Leonidas