简体   繁体   中英

On click event on any known word

I have a paragraph with some text like

"This is a bad paragraph. The good things is, this is bad. Do you know what is the bad side of it? Very bad, why you do not know this."

How can I fire an event on click any of the "bad" word. without replacing the 'bad' word by <span class="good-class">bad</span> or anything else ?

What you want to achieve is not possible using only selectors. Since selectors select entire elements. But, you can do little trick here as:

 var $el = $(".my-text"), html = $el.html(); // Replace with spans html = html.replace(/\\b(bad)\\b/ig,"<span class='bad-text'>$1</span>"); // Update content $el.html(html); // Assign click handler to those new elements $(".bad-text").on("click", function(e) { alert(this.textContent); }); 
 .bad-text{color:red;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p class="my-text"> Bad! This is a bad paragraph. The good things is, this is bad. Very bad, why you do not know this. Simbad is a badass </p> 

First replace the word 'bad' with some selector and then bind that selector.

My initial thought is that you could get the innerHTML of the element and then put spans around the text that says 'bad' and add an eventListener to them. Of course if you have access to the html, you could just put spans around them to begin with.

Select your paragraph in the DOM, either by Id or TagName or something - it's hard to tell you which without the original html.

Then replace the word 'bad' with 'bad', next access all those spans and add event listeners to them. Inside the event listener do a double check that the span contents is 'bad', then do whatever code you want.

var el = document.getElementById("this-text");
var text = el.innerHTML;
var newText = text.replace(/\bbad\b/g, "<span>bad</span>");
el.innerHTML = newText;
var spans = el.getElementsByTagName('span')
for (let i=0; i<spans.length; i++) {
  spans[i].addEventListener('click', function() {
    if(this.innerHTML === 'bad') {
      alert('You clicked bad') // put whatever you want here
    }
}, false);
}

Also here is a fiddle https://jsfiddle.net/BrettEast/attg0zqz/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM