jQuery inside each bind only function to end element

I am trying to bind one function to dynamically created elements by passing different variables to it for each group in the array. But the code below only binds the function to the final element of the array:

<div id="pbody">My dogs chase cats for canine fun.</div>
<script>
function picturekeywords() {
    $(wops).each(function(index) {
        var $this = this;
        var keyword = this.keywords.split(',');
        $(keyword).each(function() {
            var rex = new RegExp('((\\w|\\b|\'|\"|‘||"|")*' + this + '(\\w|\\b|\'|\"|‘||"|")*)', 'gi');
            $('#pbody').html($('#pbody').html().replace(rex, '<span class="wop">$1</span>'));
        });
        $('.wop').on('mouseenter', {wopobj:$this}, wop);
        $('.wop').attr('class', 'woptrig');
    });
    $('.woptrig .woptrig').each(function() {
        $(this).after($(this).html());
        $(this).remove();
    });
}
picturekeywords();

function wop(event) {
    var wopobj = event.data.wopobj;
    console.log(wopobj.picture);
}

var wops = [{keywords:'dog,canine', picture:'dog.jpg'}, {keywords:'cat,feline', picture:'cat.jpg'}];
</script>

      

The desired result is to register the name of the image for the keyword hovered over. But this only works for the latter.

http://jsbin.com/doyoxu/1/edit?html,css,js,console,output

I think it looks like a closure problem, but can't seem to solve it. Any ideas?

+3


source to share


1 answer


Eureka! The replace function changed the entire text every time, not just the matches. So I split the loop in two, binding all functions to the last one. Sort criterion. :)



0


source







All Articles