the problem:
let's have div text this
<div id=”bla”>one 2 3 4 five</div>
i want able programmatically take substring , wrap <div>
handler attached (say onlick). want able multiple times different part of text in end div can end looking this:
<div id=”bla”>one <div id=”bla2”>two</div> 3 <div id=”bla4”>four</div> five</div>
the problem how it?
some thoughts:
potentially, if want wrap string 2 div, if take whole div content using html()
, substring before , after two, .empty()
on div , .append(beforesubstring, <two wrapper handler>, afterstring)
– looks good, put beforesubstring , aftersubstring “” , remove previous handlers. want keep previous handlers , don’t need “” since messes things me.
any thoughts? :)
you first need cache element's content var cont = $("#bla").text();
use cont
before inserting wrappers (using regexp suppose...) , placing result element $("#bla").html(regexmodifiedcont);
example:
var $contentel = $("#bla"); var content = $contentel.text(); // cache original content! $("#query").on("input", function(){ var reg = new regexp("("+ $.trim(this.value) +")", "ig"); $contentel.html( content.replace(reg, "<span class='clickable'>$1</span>") ); }); $("body").on("click", ".clickable", function(){ alert( $(this).text() ); });
.clickable{ background:gold; cursor:pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> write text take <input id=query type=text> <div id=bla>one 2 3 4 five</div>
Comments
Post a Comment