简体   繁体   English

如何在新标签页/链接中打开预先放置的div?

[英]How to make a div that is inside prepend open in a new tab/link?

How can I make a div open a new link when it has a function or onclick hooked to it? 当div具有功能或钩住onclick时,如何使div打开新链接? I've been trying the following below but nothing seems to work, tbe div never includes the new link. 我一直在尝试以下操作,但似乎没有任何效果,因为div从未包含新链接。

jQuery.prepend('<div class="dropdown">' + r + closer + "</div>"))

I've tried adding javascript to make the bugme class include a new link but no luck so far.. 我尝试添加JavaScript,以使Bugme类包括新链接,但到目前为止还没有运气。

jQuery(".dropdown").on("click", function(e) {
    location.href = "www.google.com.com";
}

I also tried including onclick="location.href='http://www.google.com';" 我还尝试过包括onclick="location.href='http://www.google.com';" in the code but it did not work, why doesn't the following code allow a new link? 在代码中,但是没有用,为什么下面的代码不允许新的链接?

Since your .dropdown is dynamically added element you need what is called event delegation . 由于.dropdown动态添加的元素 ,因此需要所谓的event delegation And instead of location.href use window.open . 而不是location.href使用window.open So write click event as below: 因此,编写click event如下:

jQuery(document).on("click",".dropdown", function(e) {
    window.open('http://www.google.com', '_blank')
}

 $('body').append($('<div class="dropdown">Click me</div>')); jQuery(".dropdown").on("click", function(e) { location.href = "www.google.com.com"; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

this also worked try it 这也可以尝试

FYI; 仅供参考;
This code doesnot work 此代码不起作用

jQuery(".dropdown").on("click", function(e) {
    location.href = "www.google.com.com";
}

Reason: 原因:
the jQuery have no idea of any element with class dropdown since it is inserted in runtime and the event handler for newly added item is not assigned. jQuery不知道具有class dropdown的任何元素,因为它是在运行时插入的,并且未分配新添加项目的事件处理程序。

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. 委派事件的优势在于,它们可以处理来自后代元素的事件,这些事件在以后的时间添加到文档中。 By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. 通过选择保证在附加委托事件处理程序时会出现的元素,您可以使用委托事件来避免频繁附加和删除事件处理程序的需要。

Here the document object is guaranteed to be present always. 这里保证document对象始终存在。

jQuery(document).on("click", ".dropdown", function(e) {

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

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