简体   繁体   English

空href导致document.ready被触发

[英]empty href causing the documents.ready to fire

in reference to 在参照

Is an empty href valid? 空的href有效吗?

in my case i was using an empty href and it was causing documents.ready to fire again. 在我的情况下,我使用的是空的href,这会导致document.ready重新触发。 Here is my html: 这是我的html:

<li><a onclick="numberOfmonthsToloadInDatabase(this)" href="" id="12Monat">12 Monat</a></li>

and when i removed it then it did not fire document.ready. 当我删除它时,它没有触发document.ready。 I don't understand this behaviour, any explanation would be very helpful. 我不了解这种行为,任何解释都将非常有帮助。 i couldn't post it in the comments as i do not have enough points to add a comment on any post. 我无法在评论中发布它,因为我没有足够的观点在任何帖子上添加评论。 Thanks. 谢谢。

From your example I have to question, why are you using a link tag? 从您的示例中,我不得不质疑,为什么要使用链接标记? Since you only want the onclick event to fire you should use a span and eventually use css cursor:pointer; 由于只希望触发onclick事件,因此应使用span并最终使用css cursor:pointer; to give indication that it is clicable. 表示它是可以怀疑的。

 function numberOfmonthsToloadInDatabase(evt) { alert("your clicked"); } 
 li span { cursor:pointer; } 
 <li><span onclick="numberOfmonthsToloadInDatabase(this)" id="12Monat">12 Monat</span></li> 

This way you prevent the default link behavior for when there is no URL specified. 这样,您可以防止未指定URL时的默认链接行为。 You have less work this way instead of using javascript preventDefault() to prevent the link from executing it's default behavior. 用这种方法可以减少工作量,而不是使用javascript preventDefault()来防止链接执行其默认行为。

As other people have told you href causes page to reload, so you got the option to use href="javascript:void(0);" 正如其他人告诉您的那样,href原因页面会重新加载,因此您可以选择使用href="javascript:void(0);" or href="#" in order to avoid the page to reload, if you want to keep the underlined link style you get when using href tag. href="#"以避免重新加载页面,如果要保留使用href标记时带下划线的链接样式。

e.preventDefault() in the method won't work, because the parameter passed to the function isn't an event. e.preventDefault()无效,因为传递给函数的参数不是事件。 It's the link element itself. 它是链接元素本身。

AFAIU you're trying to create some months option for your users. AFAIU,您正在尝试为您的用户创建一些月份的选项。 A more modern aproach would be to use data-something attributes. 一个更现代的方法是使用数据属性。 You could use them like this: 您可以这样使用它们:

 function numberOfmonthsToloadInDatabase(link) { console.log(link.dataset.months); } 
 <li> <a onclick='numberOfmonthsToloadInDatabase(this)' href='#' data-months='12'> 12 Monat </a> </li> <li> <a onclick='numberOfmonthsToloadInDatabase(this)' href='#' data-months='10'> 10 Monat </a> </li> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM