Javascript 如何通过使用href更改url来调用或显示div?
我试图显示一个当前隐藏在body标记中的div。通过使用锚定标记属性href更改url。如下所示--- 我不知道为什么这不起作用,但我用下面不同的方式告诉你Javascript 如何通过使用href更改url来调用或显示div?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我试图显示一个当前隐藏在body标记中的div。通过使用锚定标记属性href更改url。如下所示--- 我不知道为什么这不起作用,但我用下面不同的方式告诉你 <a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors </a> 但是我不想要“唱”,我怎么能解决它。帮我体验一下兄弟们。提前谢谢。如果你希望导航正常,你必须使用散列。一旦
<a id="ai" href="#managevendors" class="tablink" onclick="openCity('managevendors')">Manage Vendors
</a>
但是我不想要“唱”,我怎么能解决它。帮我体验一下兄弟们。提前谢谢。如果你希望导航正常,你必须使用散列。一旦您这样做,您就不需要检查它,您只需显示该部分:
$(“#ai”)。点击(“点击”,开放城市);
函数openCity(){
//此代码正在运行的唯一原因是单击了链接。
//不需要测试它。
$(“#managevendors”).show();
}
嗨,你好吗
我认为这里的问题是,当您应该使用按钮时,您正在使用锚定标记。第一种方式不起作用的原因是单击链接时页面刷新
尝试将您的
更改为据我所知,您很可能需要href=“#xyz”
和哈希。这将保持客户端逻辑处于活动状态,而无需尝试解析url,并免费绕道服务器。如果你想捕捉那部分,就把它放在本地
我建议从HTML中删除onclick处理程序。要捕获链接,可以使用jQuery保持HTML“干净”。如果出于某种奇怪的原因必须这样做,那么您可以引用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;
}
正如Scott对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作为入口点,请注意,这只会在加载事件=>共享链接并有人单击它(附加#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; }
如果不使用#
,就不会有散列。如果您不使用它,那么您需要为虚拟路径配置服务器,如果您希望href在地址栏参考中显示有关位置的信息,则可能会使其更通用,以便在其他链接上使用,但是让我们先关注基本HTML和JS的工作。仅供参考,OP是通过一个内联HTML事件属性捕获click
事件的。
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');
}
// 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');
}
.city { display: none; }
.city.active { display: block; }