简体   繁体   English

如何在 jQuery 移动导航栏中添加/删除元素?

[英]How do I add/remove elements in a jQuery Mobile navbar?

In jQuery Mobile, lets say I have the following navigation bar:在 jQuery Mobile 中,假设我有以下导航栏:

<div data-role="navbar">
    <ul>
        <li><a id="item1">Item 1</a></li>
        <li><a id="item2">Item 2</a></li>
        <li><a id="item3">Item 3</a></li>
    </ul>
</div>

I can then just use jQuery to remove an item to make this look like:然后我可以使用 jQuery 删除一个项目,使其看起来像:

<div data-role="navbar">
    <ul>
        <li><a id="item1">Item 1</a></li>
        <li><a id="item3">Item 3</a></li>
    </ul>
</div>

However, jQuery Mobile still renders it as if there are three tabs, and in the middle one, there is just nothing there.但是,jQuery Mobile 仍然将其渲染为好像有三个选项卡,而在中间的一个选项卡中,什么都没有。 So instead of it being spaced out with each tab taking 1/2 of the width, each of the two remaining tabs just takes 1/3 of the width.因此,不是每个选项卡占用 1/2 宽度,而是每个选项卡占用 1/3 宽度。

I looked closer and jQuery Mobile automatically adds a class to the <ul> element called "ui-grid-b" and if I change that manually to "ui-grid-a" it then looks fine and the two tabs take up the whole width.我仔细看了看,jQuery Mobile 自动将 class 添加到名为“ui-grid-b”的<ul>元素中,如果我手动将其更改为“ui-grid-a”,它看起来很好,两个选项卡占据了整个宽度。 However, changing those classes manually seems too hackish and I'm guessing there is a better way to do it.但是,手动更改这些类似乎太老套了,我猜有更好的方法来做到这一点。 Any ideas?有任何想法吗?

I didn't figure out a great solution, but I at least figured out a less hacky one.我没有想出一个很好的解决方案,但我至少想出了一个不那么老套的解决方案。

For my problem, I at least know all of the elements I want in my navbars ahead of time, so I can simply construct several sets of navbars and turn them on or off depending on certain situations.对于我的问题,我至少提前知道我想要在导航栏中包含的所有元素,因此我可以简单地构建几组导航栏并根据某些情况打开或关闭它们。 Thus, the HTML looks like phil's solution, but the JS for his solution would instead look like:因此,HTML 看起来像 phil 的解决方案,但他的解决方案的 JS 看起来像:

$('#navbar1').hide();
$('#navbar2').show();
$('#page1').page();

Try this:尝试这个:

<script type="text/javascript">
    function addItem() {
        // create the navbar element
        var li = $("<li></li>");
        var a = $("<a></a>");
        var navbar = $("#navbar1");

        a.attr("id", "item4").text("Item 4");
        li.append(a);
        // remove the JQM auto-init classes
        navbar.find("*").andSelf().each(function(){
            $(this).removeClass(function(i, cn){
                var matches = cn.match (/ui-[\w\-]+/g) || [];
                return (matches.join (' '));
            });
            if ($(this).attr("class") == "") {
                $(this).removeAttr("class");
            }
        });

        // destroy the navbar widget object
        navbar.navbar("destroy");

        // append the newly created element
        li.appendTo($("#page1 ul"));

        // re-init the navbar
        navbar.navbar();
        console.log(navbar.data());
    }
</script>

I guess you already know how to remove an element from navbar now.我猜你现在已经知道如何从导航栏中删除元素了。

Not really a working example but: http://jsfiddle.net/ZsSHE/10/不是一个真正的工作示例,但: http://jsfiddle.net/ZsSHE/10/

<div data-role="page" id="page1"> 
    <div data-role="content"> 
        <div data-role="navbar" id="navbar1">
            <ul>
                <li><a id="item1">Item 1</a></li>
                <li><a id="item2">Item 2</a></li>
                <li><a id="item3">Item 3</a></li>
            </ul>
        </div>
        <br />
        <div data-role="navbar" id="navbar2">
            <ul>
                <li><a id="item4">Item 4</a></li>
                <li><a id="item5">Item 5</a></li>
            </ul>
        </div>
    </div><!-- /content --> 
</div><!-- /page --> 

JS JS

$('#item3').remove();
$('#page1').page();

You can add buttons to a jQuery Mobile navbar by adding plain links (A), and then calling the navbar() method on the navbar element itself.您可以通过添加普通链接 (A) 将按钮添加到 jQuery 移动导航栏,然后在导航栏元素本身上调用 navbar() 方法。

For example: in HTML you place an empty navbar like this:例如:在 HTML 中,您放置一个空导航栏,如下所示:

  <div data-role="navbar" data-theme="a">
    <ul id="myNavbar"></ul>
  </div>

Than in JavaScript you do the following:比在 JavaScript 中您执行以下操作:

// creating new buttons
$("#myNavbar").append('<a href="#" class="ttxButton">button 1</a>');
$("#myNavbar").append('<a href="#" class="ttxButton">button 2</a>');
$("#myNavbar").append('<a href="#" class="ttxButton">button 3</a>');

// calling the navbar method
$("#myNavbar").navbar();

Refreshes the NavBar without recreating the component刷新 NavBar 而不重新创建组件

function refreshNavbar(el) {
    var ul = el.children("ul"),
        childCount = 0, cls, visibleEl,
        children = ul.children("li"),
        clsList = ["ui-grid-solo","ui-grid-a","ui-grid-b","ui-grid-c","ui-grid-d","ui-grid-duo"],
        clsArr = ["ui-grid-solo","ui-grid-a","ui-grid-b","ui-grid-c","ui-grid-d","ui-grid-duo ui-grid-a"];

    for (var i = 0, j = children.length; i < j; i++) {
        child = $(children[i]);
        if (child.is(":visible")) {
            childCount++;
        }
    }

    cls = clsArr[childCount-1];
    if (childCount == 1) {
        visibleEl = ul.children("li:visible");
        if (!visibleEl.hasClass("ui-block-a")) {
            visibleEl.addClass("ui-block-a");
        }
     } else {
        ul.children("li").removeClass("ui-block-a");
        ul.children("li:first").addClass("ui-block-a");
     }

    //remove existing grid class
    var rx = new RegExp(clsList.join("|"), "gi");
    var oldCls = ul.attr("class").replace(rx, function (matched) {
        return "";
   });

    //set new grid class, preserving existing custom clases
    ul.attr("class", oldCls + " "+ cls);
}

Fiddle小提琴

http://jsfiddle.net/tM3KR/ http://jsfiddle.net/tM3KR/

You should simply use $('#navbar').navbar('refresh').您应该简单地使用 $('#navbar').navbar('refresh')。 #navbar could be any id or element reference. #navbar 可以是任何 id 或元素引用。

The .navbar method by itself, does not seem to work on jquery mobile 1.4.2. .navbar方法本身似乎不适用于 jquery mobile 1.4.2。 I had to perform a destroy first and it seems the styles get reapplied.我必须先执行销毁,似乎 styles 被重新应用。

FYI, this will work as long as the buttons added do not wrap.仅供参考,只要添加的按钮不换行,这将起作用。 If you add enough buttons for the navbar to wrap them, the style applied is not totally correct.如果您为导航栏添加足够多的按钮来包装它们,则应用的样式并不完全正确。

The code would look like代码看起来像

$('#yournavbarDIV').navbar("destroy");
$('#yournavbarDIV').navbar();

after you append your li elements.在你 append 你的 li 元素之后。

the html html

<div id="def"></div>

the javascript javascript

$("#def").append("<ul id='abc'></ul>");
$("#abc").append('<li><a href="#">111</a></li>');
$("#abc").append('<li><a href="#">222</a></li>');
$("#abc").append('<li><a href="#">333</a></li>');
$("#def").navbar();

I had the same problem and this is what I did.我有同样的问题,这就是我所做的。

In HTML在 HTML

<div data-theme="b" data-role="footer" data-position="fixed">
  <div class="maintenance_tabs">
  </div>
</div>

And then in the JS function, I did this然后在 JS function 中,我这样做了

var mynavbar = '<div data-role="navbar" data-iconpos="top" class="maintenance_tabs">'
                +'  <ul>'
                +'    <li>'
                +'      <a href="log.html" data-transition="fade" data-theme="b" data-icon="bars">'
                +'        View Log'
                +'      </a>'
                +'    </li>'
                +'    <li>'
                +'      <a href="'+ data.page +'" data-transition="fade" data-theme="b" data-icon="plus">'
                +'        New Entry'
                +'      </a>'
                +'   </li>'
                +'    <li>'
                +'      <a href="" data-transition="fade" data-theme="b" data-icon="back" onclick="return logoutAction();">'
                +'        Logout'
                +'      </a>'
                +'   </li>'
                +'  </ul>'
                +'</div>';
  $(".ui-page-active .maintenance_tabs").empty();
  $(".ui-page-active .maintenance_tabs").append(mynavbar).trigger('create');

I called the.empty() everytime so that it doesn't repeat the navbar again and again.我每次都调用 the.empty() 以便它不会一次又一次地重复导航栏。 Hope this helps someone.希望这可以帮助某人。

Thanks.谢谢。

I have a lot of problems changing a navbar content.我在更改导航栏内容时遇到了很多问题。 This because the new content/buttons do not acting as normal这是因为新的内容/按钮不能正常工作

Actually, it doesn't fully work in 1.4.3: the newly created tabs keep the active state when you click on another tab – Matthieu实际上,它在 1.4.3 中并不能完全工作:当您单击另一个选项卡时,新创建的选项卡会保持活动的 state – Matthieu

Searching deep in source I found that navbar is doing this:深入搜索源代码,我发现导航栏正在这样做:

$navbar.delegate( "a", "vclick", function( /* event */ ) {

So, even if you destroy the navbar and recreate it, this event will be fired twice and this will break the normal behaviour.因此,即使您销毁导航栏并重新创建它,此事件也会被触发两次,这将破坏正常行为。 This will work:这将起作用:

navbar = $("#my-navbar");
navbar.navbar("destroy");
navbar.undelegate();

navbar.html("<ul><li><a href=\"#area1\">First  option</a></li><li><a href=\"#area2\">Second option</a></li></ul>");
navbar.navbar();
$('#my-tabs').tabs('refresh');

This has drive me crazy many days in a row... I hope it will help you.这让我连续很多天发疯......我希望它会对你有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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