我有一个页面,可以使菜单下拉以实现响应行为。所以很明显,只有当屏幕较小时,选择标签才会出现在图片中。我想将 jquery 应用于该选择框以及当时动态添加的其他两个按钮。
我提到这个问题: Event binding on dynamically created elements?
但这并没有帮助我解决问题。任何人都可以解释我哪里出了问题吗?
我用了this jquery 使其在我的页面中出现下拉菜单。-仅供引用,如果有人需要。
这是我尝试过的:
<div id="nav" role="navigation">
<a href="#nav" title="Show navigation" id="shownav">
choose one
<img src="images/dropmenu-arrow.png" alt="" class="droparrow">
</a>
<a href="#" title="Hide navigation" id="hidenav">
choose one
<img src="images/dropmenu-arrow.png" alt="" class="droparrow">
</a>
<ul class="clearfix" id="kat-drop">
<li><a href="#">list item 1</a></li>
<li><a href="#">list item 2</a></li>
<li><a href="#">list item 3</a></li>
</ul>
</div>
<script src="js/doubletaptogo.min.js"></script>
<script>
$( function()
{
$( '#nav li:has(ul)' ).doubleTapToGo();
});// upto this-it runs fine giving me dropmenu for desired screen
$(document).on("click",$("#shownav"), function(){
//alert("clicked"); // this didn't work neither the rest of the code from here
if($("#kat-drop").css("display")=="block"){
$("#kat-drop").slideUp();
}
else{
$("#kat-drop").slideDown();
}
} );
</script>
编辑 - 1
好的,我按照要求将其删除。现在是:
$(document).on("click","#shownav", function(){
event.preventDefault(); // i want to prevent reloading of page too which doesn't work for now.
} );
$(document).on("click","#shownav", function(){
alert("clicked"); // Still I am not getting this alert
if($("#kat-drop").css("display")=="block"){
$("#kat-drop").slideUp();
}
else{
$("#kat-drop").slideDown();
}
} );
编辑 - 2
它既不会阻止页面重新加载,也不会向我发出警报。
$(document).on("click","#shownav", function(event){
event.preventDefault(); // i want to prevent reloading of page too which doesn't work for now.
} );
$(document).on("click","#shownav", function(event){
alert("clicked");// not working yet
} );
最佳答案
只需更改您的代码:
$(document).on("click",$("#shownav"), function(){
对此:
$(document).on("click", "#shownav", function(){
正如,使用 event delegation
时的正确语法就像:
$( selector ).on( events, selector, handler)
<小时/>
更新
But still it is refreshing the whole page which is the only thing i want to prevent along with hide/show the menu.
您只需要使用.preventDefault()来阻止 anchor 的默认点击操作。像:
$(document).on("click", "#shownav", function(e){
e.preventDefault();
// your code here..
});
<小时/>
在您编辑的代码中:
$(document).on("click", "#shownav", function (event) {
event.preventDefault();
});
$(document).on("click", "#shownav", function (event) {
alert("clicked"); // not working yet
});
您已将两个事件处理程序附加到同一元素。只需分配一个事件处理程序,如下所示:
$(document).on("click", "#shownav", function (e) {
e.preventDefault();
alert("clicked");
});
并查看像我提供的 fiddle 演示一样的结果。
关于jquery - 在动态显示/隐藏元素上应用 Jquery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19947647/