首页 > 解决方案 > html() 似乎不适用于 li 内的 span 元素

问题描述

我有一个带有下拉菜单的引导导航标题。我正在尝试使用 html() 在其中一个下拉列表中附加一个单词,但没有成功。我尝试了 append() ,它也不起作用。我不明白,因为列表是静态的而不是动态的。

下拉菜单

<li class="dropdown">
        <a class="dropdown-toggle" data-toggle="dropdown" href="#">
        <i class="fa fa-bell fa-lg header-icon" aria-hidden="true"></i>
         .'<span class="header-li">'.$Notifications.'</span>
         <i class="fas fa-caret-down header-icon"></i>
        <ul class="dropdown-menu">
         <li><a class="" href="#">'.$Youhavenewnotifications.'</a></li>
         <hr>
          <li><a id="alist2345" href="#">
           Hi visitor from <span id="userRegion"></span>!
           We have many customers like you from <span id="userCity"></span>!
        </a></li>
        </ul>
      </li>

jQuery

$( window ).load(function() {
//get user location details
$.get("http://ipinfo.io", function (response) {

 var userCity = response.city;
 var userRegion = response.region;

 //append to header
  $('#userRegion').html(userRegion);//does not work
  $('#userCity').html(userCity);//does not work
   //$('#alist2345').html(userRegion + userCity);//EDIT: THIS IS JUST AN EXAMPLE to show that this one works but it is obviously not the desire outcome

}, "jsonp");
});

标签: javascriptjquery

解决方案


它确实html按预期将 注入到跨度中,但最后一次html插入会覆盖以前的更改。

$('#userRegion').html(userRegion);
$('#userCity').html(userCity);
$('#alist2345').html(userRegion + userCity); -- > This overwrites the `html` again ( and the span tags get replaced )

删除最后一条语句,它应该按预期显示。

否则你也可以试试这个。。

$('#alist2345').html($('#alist2345').html() + userRegion + userCity);

推荐阅读