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");
});

它确实按预期将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);

这是因为你在写

$('#userRegion').html(userRegion);//does not work
$('#userCity').html(userCity);//does not work

然后清除整个锚元素

$('#alist2345').html(userRegion + userCity);//works but not the desire outcome

删除

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

并将 .html(( 更改为 .text((,因为.html更改了"html",并且 .text(( 在元素中插入了一个刺痛。

$(window).on('load', function () {
$.get("https://ipinfo.io?token=yourtoken-goes-here", function (response) {
var userCity = response.city;
var userRegion = response.region;
$('#userRegion').text(userRegion);
$('#userCity').text(userCity);
}, "jsonp")
})
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
crossorigin="anonymous">
<ul>
<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>
</ul>

感谢大家的所有努力!

我发现了错误,这不是我的编程能力(呵呵(。我们基本上是这个项目的几个负责人,其中一位程序员在桌面上上传了一个重复的文件,奇怪的是应用程序正在从该文件而不是应用程序文件夹中获取数据......??

更深入地查看控制台证明这是真的。我可以看到上一个文件中的旧数据,而不是我正在处理的文件。

非常奇怪的行为,但是当我删除同事之前上传用于测试(并忘记删除(的重复文件时,一切都开始正常工作。

非常奇怪的行为,但现在没事了。

Ps:如果您知道为什么会发生这种情况,请告诉我,因为我想了解更多有关该主题的信息!

最新更新