0

I am working on a tampermonkey / greasemonkey script and want to make a ticket ID clickable to search for it.

I already found on Stack Overflow, that I should use .on() or .live() to create the listeners.

My problem is, that I am working with an additional script and I don't have the possibility to change to original source code.

What can I do to keep the listeners?

I am working with this single line in this case to replace a 9 digit number, which is not a part of an html attribute:

$(this).html($(this).html().replace(/\b([0-9]{9})\b(?!(?:(?!<\/?[ha].*?>).)*<\/[ha].*?>)(?![^<>]*>)/,'<a href="example.cpm?search=$1" target="_blank">$1</a>'));

$(this) could be something like this: <span class="alert">Hehe</span>123456789

with the listener declaration in the head:

$('span.alert').click(function(){
    alert($(this).html());
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Michael Walter
  • 1,427
  • 12
  • 28
  • Can you post the original HTML code being replaced? – Scimonster Oct 23 '14 at 17:39
  • 1
    don't use `.html(.html().replace` if you want to keep the events. Modify only the text where the number is. – Kevin B Oct 23 '14 at 17:41
  • @Scimonster: I added an example to my post – Michael Walter Oct 23 '14 at 17:46
  • 4
    The reason it fails is that you're destroying the previous elements, which had handlers attached to them, and creating new elements in their place. To do what you want to do, you'll have to do **much** more work: Basically, you need to find the text nodes where the numbers occur (and decide whether you want to handle the case where they span nodes), then split those text nodes to insert the link, moving the number into the link. It's not hard, but it's non-trivial. This answer may give you a leg up: http://stackoverflow.com/a/5158204/157247 – T.J. Crowder Oct 23 '14 at 17:47
  • @KevinB: I already had the same idea. The problem is, that I don't know how to traverse every text-node in my jQuery result. Any suggestions? – Michael Walter Oct 23 '14 at 17:47
  • No need to use `on()` or `live()` (which is deprecated) if all your elements are present on DOM load. – isherwood Oct 23 '14 at 17:48
  • While it is possible to use delegated event handlers to handle the problem, the idea is wrong. You need to perform find/replace on the _text content_ inside the HTML. Search on SO for "highlight text inside a string" and look for solutions that DO NOT use RegEx/innerHTML. – Salman A Oct 23 '14 at 17:52
  • Thanks a lot for the suggestions. I found my working solution (with modifications for my problem) her in this comment: from http://stackoverflow.com/a/5160224/1443949 Thanks @T.J.Crowder for the good hint – Michael Walter Oct 23 '14 at 18:42

0 Answers0