如何编写一个替换标签内文本的js?

时间:2014-07-15 21:46:03

标签: javascript html css drop-down-menu toggle

如何编写一个替代标签内文字的js? 我有一个使用此javascript的下拉移动菜单:

toggle.js

$(function ()
{
var $window = $(window),
    $nav = $('nav'),
    $button = $('button');

$button.on('click', function ()
{
    $nav.slideToggle();
});

$window.on('resize', function ()
{
    if ($window.width() > 320)
    {
        $nav.show();
    }
});
});

Here is the section of HTML
<button>Select Destinations
<img src="images/down-arrow.png" width="20" height="20"/>
</button>
<nav id="menu">     
<a href="#">Philadelphia</a>
<a href="#">United States of America</a>
<a href="#">Philippines</a>
<a href="#">Long Destinations Names</a>
<a href="#">Some Destination</a>
<a href="#">Australia</a>
</nav>

我需要将“选择目的地”替换为下拉菜单中的所选按钮。恩。如果我选择“洛杉矶”,它应该将“选择目的地”替换为“洛杉矶”。我尝试了下拉列表,但它看起来与不同的设备不同。

任何人都可以分享一些信息吗?提前谢谢。

4 个答案:

答案 0 :(得分:1)

在JQuery中,通过以下方式访问标签内的文本:

$(obj).text();

$(obj).html();

在没有任何参数的情况下调用它们,它会检索当前值,传入您自己的字符串并替换它里面的内容。

答案 1 :(得分:0)

如果您正在使用jquery,则可以通过以下方式替换标记中的元素:

$('.myselector').html('stuff to put inside my selector');

答案 2 :(得分:0)

您可以这样做:

//Javascript
$("nav#menu a").click(function()
{
    $("span").text($(this).text());
});

// HTML
Here is the section of HTML
<button><span>Select Destinations</span>
<img src="images/down-arrow.png" width="20" height="20"/>
</button>
<nav id="menu">     
<a href="#">Philadelphia</a>
<a href="#">United States of America</a>
<a href="#">Philippines</a>
<a href="#">Long Destinations Names</a>
<a href="#">Some Destination</a>
<a href="#">Australia</a>
</nav>

答案 3 :(得分:0)

不接触任何HTML

img_arrow = '<img src="images/down-arrow.png" width="20" height="20"/>';

$('#menu a').click(function(e){

    $('button').html($(this).html() + img_arrow);

    e.preventDefault();
});

请参阅jsFiddle