繁体   English   中英

<a>单击</a>该<a>链接时,在JQuery颜色框中</a>打开<a>链接</a>的URL

[英]Opening the URL of a <a> link in JQuery colorbox when it is clicked

我需要有关此JQuery代码的帮助。.当涉及到JQuery时,我仍然是一个新手,但是我有很多代码可以进行测试..您知道万一需要时,这里是代码。

<script type="text/javascript">
//onload popup
$(function()
{
    $(window).bind('load', 
        function(e) 
        {
            $.colorbox({opacity:0.3, href:"ext/popup.php"}); 
        });
});

</script>

现在这一次,我不想加载页面,然后让表单弹出。.我不想像链接一样单击。.有什么建议吗?

$(function()
{
    $('#linkid').click(function(e) 
        {
            e.preventDefault();
            $.colorbox({opacity:0.3, href: this.href}); 
        });
});

并创建一个像这样的链接

<a href="ext/popup.php" id="linkid">click me</a>

更新资料

如果要将此逻辑应用于多个链接,则应使用类而不是ID

<a href="ext/popup.php" class="colorbox">click me</a>

并为jquery定位他们

$('.colorbox').click(...)

评论

对代码的通用注释,您无需使用$(function(){..})$(window).bind('load'
第一部分将事件绑定到准备就绪的DOM上。 第二个是DOM负载。
由于load总是 ready事件之后发生,因此您可以直接执行

$(window).load(function(){...});

但是,只有在需要在运行代码之前完全加载了子元素( 通常是images )时,才应使用加载。
读取: http : //api.jquery.com/load-event/

$('a#yourLinkId').click(function(e){
  // prevents default behaviour
  e.preventDefault();

  // your stuff
  $.colorbox({opacity:0.3, href:"ext/popup.php"}); 

});

没问题。 您可以在Stackoverflow中询问有关JQuery的任何问题,我们会尽力提供帮助。

关于你的问题。 我认为您想使用JQuery在ColorBox中加载页面,而不是在主窗口中加载URL的默认操作。

您需要做两件事:

  1. 将事件处理程序绑定到所有锚标记( <a> ),以便每当单击它们时都将运行事件。
  2. 阻止默认事件处理程序打开URL(preventDefault)

您可以将事件绑定到所有锚标记,如下所示:

//for all links that exist on this page up to when this line is executed
$("a").click(function(){...});

但是我建议使用on()按钮绑定事件。 这样,所有<a>标记都将运行此事件处理程序,即使它们是在事件绑定代码运行之后创建的。

//for all links that are created on this page even after this lines of code is executed
$("a").on( "click", function(){...});

为了防止默认操作(浏览页面),您只需使用preventDefault()方法:

//assuming event argument is called e
e.preventDefault();

话虽如此,您的代码将如下所示:

<script type="text/javascript">
//this will run when the current document is loaded
$(document).ready(function(){
    $("a").on("click",function(e){
        e.preventDefault();
        //$(this).attr("href") contains the href attribute of the <a> tag
        $.colorbox({opacity:0.3, href:$(this).attr("href")});
    });
});
</script>

暂无
暂无

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

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