Jquery Mobile hash issue when using basic id selectors
Example:
http://test.com/test.php
with something like:
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.css" />
<script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0b2/jquery.mobile-1.0b2.min.js"></script>
</head>
<body>
<div data-role="page" class="type-interior" id="home">
<div data-role="wrapper" class="type-home">
&开发者_开发问答lt;div data-role="header" data-position="inline" id="header">
</div>
<div data-role="content" class="content">
<div id="show" style="display:none">Hi!!</div>
<a onClick="$('#show').show();">Show!</a><br />
<a href="test.php?a=<?=rand()?>">Next page</a>
</div>
</div>
</div>
</body>
</html>
When you click 'Show!' it works fine, however, when you click Next page and then Show! it doesn't work anymore. This seems to be due to the # in the url after clicking the link.
This can be solved by putting:
$('ul[id=show]').show();
or
$('ul#show').show();
instead, however, I would really like to know why this happens.
In firebug, there is a difference as well;
http://o7.no/oYbOPK
The top one doesn't work, shows nothing on the page with a # in the uri, while the bottom one does work on that page.
And this is how it looks when there is no #, just test.php;
http://o7.no/pvCyP7
Combined; http://o7.no/qo6L65
The divs appear greyed out when requested by the id selector only; why is that?
Thanks for helping out; I keep bumping into this issue every time and i'm really curious to why it happens at all.
After the Ajax call, if you look in Firebug you will see that your page is twice present in the DOM, and so, there are two <div data-role="page" id="home">
and two id="show"
also.
So when you trigger $("#show").something(), it's always the FIRST element with this id which is trigerred. Don't forget that an ID must be unique on a xhtml page.
When you use a syntax like ul[id=show]
, ul#show
, jquery will trigger all the objects, not only the first. That's why it works.
A possible workaround is to use the page as a namespace
<div data-role="page" class="type-interior" id="home">
<div data-role="wrapper" class="type-home">
<div data-role="header" data-position="inline" id="header"></div>
<div data-role="content" class="content">
<div class="show" style="display:none">Hi!!</div>
<a class="link" href="#">Show!</a><br />
<a href="test3.htm?id=3">Next page</a>
</div>
</div>
</div>
<script type="text/javascript">
$('#home').live('pagecreate',function(event){
$(".link", this).live('click', function(page) {
$(this).closest('div[data-role=page]').find(".show").show();
});
});
</script>
But it's not the best solution. If your pages are differents, give them differents ids or use classes and find the good ancestor !
Just had a similar problem, this works better -
$.mobile.activePage.find('#show').show();
精彩评论