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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6285869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 20:09:39  来源:igfitidea点击:

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

javascriptjqueryjquery-mobile

提问by Spike

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. 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.

但是,jQuery Mobile 仍然将其呈现为好像有三个选项卡,而在中间的一个选项卡上,什么也没有。因此,与其隔开每个标签占用 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. However, changing those classes manually seems too hackish and I'm guessing there is a better way to do it. Any ideas?

我仔细看了看,jQuery Mobile 会自动向<ul>名为“ui-grid-b”的元素添加一个类,如果我手动将其更改为“ui-grid-a”,它看起来不错,两个选项卡占据了整个宽度。但是,手动更改这些类似乎太黑了,我猜有更好的方法来做到这一点。有任何想法吗?

采纳答案by Spike

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();

回答by bean

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.

我想您现在已经知道如何从导航栏中删除元素了。

回答by knee-cola

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),然后在导航栏元素本身上调用 navbar() 方法来向 jQuery Mobile 导航栏添加按钮。

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();

回答by Phill Pafford

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();

回答by Richard A

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/

回答by SuperNova

You should simply use $('#navbar').navbar('refresh'). #navbar could be any id or element reference.

您应该简单地使用 $('#navbar').navbar('refresh')。#navbar 可以是任何 id 或元素引用。

回答by dcapelo

The .navbarmethod by itself, does not seem to work on jquery mobile 1.4.2. I had to perform a destroy first and it seems the styles get reapplied.

.navbar方法本身似乎不适用于 jquery mobile 1.4.2。我必须先进行破坏,而且似乎重新应用了样式。

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.

在添加 li 元素之后。

回答by Junior

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 中并不完全有效:当您单击另一个选项卡时,新创建的选项卡会保持活动状态 – 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.

这让我连续几天发疯......我希望它会帮助你。

回答by Muhammad Tanweer

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函数中,我这样做了

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. Hope this helps someone.

我每次都调用 .empty() 以便它不会一次又一次地重复导航栏。希望这可以帮助某人。

Thanks.

谢谢。

回答by Tejesh Alimilli

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();