简体   繁体   English

任何已知单词的点击事件

[英]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 ? 而不用<span class="good-class">bad</span>或其他任何字词代替“坏”字?

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. 我最初的想法是,您可以获取元素的innerHTML,然后在标有“ bad”的文本周围放置跨度,并向其添加eventListener。 Of course if you have access to the html, you could just put spans around them to begin with. 当然,如果您可以访问html,则可以先在它们周围放跨度。

Select your paragraph in the DOM, either by Id or TagName or something - it's hard to tell you which without the original html. 通过Id或TagName或其他方式选择DOM中的段落-如果没有原始html,很难告诉您哪个段落。

Then replace the word 'bad' with 'bad', next access all those spans and add event listeners to them. 然后将“ bad”一词替换为“ bad”,然后访问所有这些跨度并向其添加事件侦听器。 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/ 另外这里还有一个小提琴https://jsfiddle.net/BrettEast/attg0zqz/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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