我正在尝试显示当前隐藏的div,并在主体tag.by中使用下面的锚定标记属性href.Like更改url
<a id="ai" href="managevendors" class="tablink" onclick="openCity()">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>当我点击这个锚标签时,我的网址肯定会基于网址changed.and,我想显示一个div。我的js代码...
function openCity() {
if (window.location.hash == "managevendors") {
$("#managevendors").show();
}
}我不知道为什么这不是working.but,我用不同的方式说,像下面..
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>和js代码.....
function openCity()
{
if (window.location.hash == "#managevendors") {
$("#managevendors").show();
}
}但是我不想要# sing,我怎么才能提前解决我的体验brothers.thanks呢?
发布于 2017-02-08 01:35:11
如果您希望导航正常工作,则必须使用散列。一旦你这样做了,你就不需要检查它了,你只需要显示这个部分:
$("#ai").on("click", openCity);
function openCity() {
// The only reason this code is running is because the link was clicked.
// No need to test for it.
$("#managevendors").show();
}<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- You have to include the hash in the href for navigation to work -->
<a id="ai" href="#managevendors" class="tablink">Manage Vendors
</a>
<div class="w3-container city" style="display: none;" id="managevendors">
<h1>hi,how are you</h1>
</div>
发布于 2017-02-08 01:36:08
我认为这里的问题是,当你应该使用按钮的时候,你却在使用锚标签。第一种方法不起作用的原因是当您单击链接时页面会刷新。
尝试将<a>更改为<button>
发布于 2017-02-08 01:40:48
据我所知,您很可能需要带哈希的href="#xyz"。这将使客户端逻辑保持活动状态,而无需尝试解决url并免费绕道到服务器。如果您要捕获这一部分,请将其保留在本地。
我建议从HTML中删除onclick处理程序。为了捕获链接,你可以使用jQuery来保持你的超文本标记语言的“整洁”。如果需要,出于某种奇怪的原因,您可以通过各种方式引用onclick="openCity(this)",这样您单击的元素将直接传递给openCity。
// vanilla
function openCity(element){
var href = element.getAttribute('href'), // expecting a hash here
id = href.substr(1), // remove the hash
target = document.getElementById(id);
target.className += " active";
return false;
}正如斯科特对jQuery所建议的那样:
//$('.tablink').on('click', openCity);
$('.tablink[href^="#"]').on('click', openCity);然后,可以通过引用单击的元素中的href来使函数动态化:
function openCity(ev){
var el = $(ev.currentTarget),
id = el.prop('href'), // expecting a hash here
target = $(id);
// since you're providing both with and without hash, the default behaviour is to follow the link, unless referenced with a hash
ev.preventDefault();
target.addClass('active');
}如果在页面上找不到该id,这将静默无效。
现在,如果您想使用url作为入口点,请注意,这只会在load event => share a link时发生,并且有人点击它(附加了#xyz )或直接在地址栏中键入。
// 1. bind the event
$(window).load(function(){
/*loadCity defined here or outside*/
loadCity();
});
// 2. define what happens
function loadCity(){
var id = window.location.hash, // expecting a hash here
target = $(id);
target.addClass('active');
}由于此解决方案仅解决了元素的状态,因此可以在CSS中制作实际的显示/隐藏部分。非常简单,就像你可能已经做过的那样,或者使用动画,转场等等。
.city { display: none; }
.city.active { display: block; }https://stackoverflow.com/questions/42096216
复制相似问题