简体   繁体   中英

Preventing jQuery mobile from setting document.title?

It looks like jQuery mobile sets document.title to the text content of data-role="header" , example:

<div data-position="fixed" data-role="header">
    <h1>This text</h1>
</div>

I have a hack workaround to prevent this as such:

$('div[data-role="page"]').bind('pageshow',function(){document.title = "My title"});

Is there a better/more semantic way to do this?

Another solution would be to copy the original document title to the data-title attribute of each page:

$(":jqmData(role='page')").attr("data-title", document.title);

The advantage of this approach over changing the title on pageshow is that it will prevent document title flicker during page transitions.

If you wrap your value around div it will not update the title. Like this:

<div data-position="fixed" data-role="header">
    <div><h1>This text</h1></div>
</div>

I would just patch jQuery mobile to remove the unwanted behaviour. It appears to be in jquery.mobile.navigation.js . You could rebuild jQuery Mobile to get the minified version again.

If you were feeling ambitious, you could even submit a bug to jQuery Mobile asking that this be an option (and possibly even write a patch yourself, if you're comfortable doing so).

The jqmData option here didn't work for me. The H1 wrapping option messed up the looks which I would need to correct through CSS. What did work for me and is actually documented by jQuery Mobile is:

http://demos.jquerymobile.com/1.1.2/docs/pages/page-titles.html

Which comes down to adding the data-title attribute to the div with data-role="page":

<div data-role="page" data-theme="a" data-title="MyPage - @ViewBag.Title">

In this particular example I'm setting the page title to "MyPage - " followed by the page title as set through MVC in the ViewBag.

$(":jqmData(role='page')").attr("data-title", document.title);

This works as proposed by @stanislaw-osinski - however, I had to use it like this to get it work in jQuery Mobile v1.4.5:

<script>
$(document).bind("pageinit", function(){
     // Patch to prevent overwriting <title></title>
    $(":jqmData(role='page')").attr("data-title", document.title);
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM