Detect click on the inner text of the element without wrapping the text in a second element

后端 未结 5 711
星月不相逢
星月不相逢 2020-12-19 21:07

I have a Div which is as big as half of my page using CSS:

CLICK ON THIS TEXT

I am trying to wr

5条回答
  •  隐瞒了意图╮
    2020-12-19 21:29

    Let's alter the content dinamically - I will make the clicking on lala available:

    one
    lala
    Script: var htmlText = $('#gig').text(); //the big divs text var children = $('#gig').children(); //get dom elements so they can be ignored later $.each(children, function (index, child) { var txt = $(child).text().trim(); if (txt != '') { //if a child has text in him htmlText = htmlText.replace(txt, 'xxx'); //replace it in the big text with xxx } }); htmlText = htmlText.split("xxx"); //split for xxx make it arrat var counter = 0; //the part when the text is added $.each(htmlText, function (i, el) { htmlText[i] = el.trim(); if (htmlText[i] != "") { //if there is something here than it's my text htmlText[i] = '' + htmlText[i] + ''; //replace it with a HTML element personalized counter++; //mark that you have replaced the text } else { // if there is nothing at this point it means that I have a DOM element here htmlText[i] = $(children[i - counter])[0].outerHTML; //add the DOM element } }); if (children.length >= htmlText.length) { //you might have the case when not all the HTML children were added back for (var i = htmlText.length - 1; i < children.length; i++) { htmlText[i + 1] = $(children[i])[0].outerHTML; //add them } } htmlText = htmlText.join(""); //form a HTML markup from the altered stuff $('#gig').html(htmlText); // replace the content of the big div $('#text').on('click', function (data) { //add click support alert('ok'); });

    See a working example here: http://jsfiddle.net/atrifan/5qc27f9c/

    P.S: sorry for the namings and stuff I am a little bit tired.

    Are you able to do this, is this what you are looking for?

    What the code does: It's making only the text inside the div although the div could have other divs as well, makes only the text that has no HTML container like a div a span a p an a or something like that and alters it adding it in a span and making it available for clicking.

提交回复
热议问题