Binding a jQuery click event to each element within a foreach loop -


I am creating a plugin that matches an element, finds a link in it and the basic element is that location Click on

I have a loop in the main body:

this return.each (function (option) {$ to_link = $ (this); // matching item link_href = $ ('A', $ to_link) .attr ('href'); // link location $ ($ to_link, $ parent). (Function () {warning (link_href); window.location = link_href; return < / Code>

which I'm running against this HTML

  & lt; div id = "a" & gt; & lt; h2 & gt;  

The problem I have is that the click function always jumps into the value of the last matching divis, even though the title of the element is the correct value

obvious To be behaviious, should be behaviious:

  • div # is the title of "title / product /" and when clicked / products /

  • div #a is the title of "thinking / thinking" and when clicked / thinking /

Instead, what Occurs:

  • div # a " Title / products / "and when clicked / thinking / (Warning says / think)

  • div # one The title of "thinking / thinking" is the title and when clicked / thinking /

i.e. div # ends with a wrong behavior i guess I have some kind of scope, but for my life I can not see it, help!

You are forgetting var in your work, Sharing variables and mixing them

  $ to_link = $ (this); // Match object link_href = $ ('a', $ to_link) .attr ('href'); // link location must be  

  var $ to_link = $ (this); // Match object var link_href = $ ('a', $ to_link) .attr ('href'); // link location  

Otherwise, link_href will maintain the last value, and it is the price at which the click handler will appear when it is called.


Comments

Popular posts from this blog

oracle - The fastest way to check if some records in a database table? -

php - multilevel menu with multilevel array -

jQuery UI: Datepicker month format -