Artifex
Artifex

Reputation: 81

jQuery Binding on the same element

I've got problem with jquery

page1.html

<div id="gold">gold value</div>
<!-- NAVIGATE -->
<a href="page2.html">Go to page 2</a>

page2.html

<div id="gold">gold value</div>
<!-- NAVIGATE -->
<a href="page1.html">Go to page 1</a>

main.js

$(document).on('pagebeforeshow',  function () {

   $('#gold').html(100);
});

This code working for page1.

When I navigate from page1 to page2 on page2 is string "gold value".

Its only working when I change main.js and page2.html like this:

$(document).on('pagebeforeshow',  function () {

   $('#gold').html(100);
   $('#gold2').html(100);
});

and when I change in page2.html

div id="gold2"

Upvotes: 1

Views: 56

Answers (1)

Sga
Sga

Reputation: 3658

Due to the page loading method of jQuery Mobile, you may have many pages in the DOM at a certain time.

jQuery Mobile uses div elements with attribute data-role="page" to represent pages. First, make sure that your pages have a unique id, it does not matter if you separate your pages in many HTML files.

Now you can access your duplicate ID element specifying the current active page:

$(document).pagecontainer("getActivePage").find("#gold");

But I really recommend avoiding duplicate IDs, even in different pages. Use a class instead:

<div class="gold">gold value</div>

and

$(".gold").html(100);

Upvotes: 4

Related Questions