简体   繁体   English

使用jQuery将属性从一个元素复制到另一个

[英]Copy an attribute from one element to another with jQuery

I have the following jQuery code which doesn't seem to be doing anything. 我有以下的jQuery代码,似乎没有做任何事情。 When the link is clicked, I'm trying to get the value of its url attribute to be copied into the iframe 's src attribute. 单击链接后,我正在尝试获取其url属性的值,以将其复制到iframesrc属性中。

Basically this is supposed to make links open up in an iframe (the content of the iframe is replaced every time a new link is clicked) instead of acting like normal links. 基本上,这应该使链接在iframe中打开(每次单击新链接时都会替换iframe的内容),而不是像普通链接一样工作。

So what is wrong with my code? 那么我的代码有什么问题呢?

$('p.tweet a').click(function(){
    var link = $(this).attr('url');
    $('iframe').attr('src',link);
})

maybe you may want to get the href attribute (and even prevent the default action) 也许您可能想要获取href属性(甚至阻止默认操作)

$('p.tweet a').click(function(ev){
    ev.preventDefault();
    var link = this.href;  // no need to call the $ function
    $('iframe').attr('src',link);
})

So what is wrong with my code? 那么我的代码有什么问题呢?

You are not canceling the default action by returning false from the click handler of the anchor you subscribed to and thus not leaving any chance for your script to execute before the browser simply redirects away from that page: 您不会通过从订阅的锚点的单击处理程序返回false来取消默认操作,因此在浏览器直接重定向离开该页面之前,脚本不会执行任何机会:

$('p.tweet a').click(function() {
    var link = $(this).attr('href');
    $('iframe').attr('src', link);
    return false;
});

And by the way notice that I've used $(this).attr('href') instead of $(this).attr('url') . 顺便说一句,我已经使用$(this).attr('href')代替$(this).attr('url') The href attribute is kinda more common to anchors than the url attribute in standard HTML, but if you have invented some markup in which anchors have an url attribute then you could give it a spin. href属性比标准HTML中的url属性更常见于锚点,但是如果您发明了一些标记,这些标记中的锚点具有url属性,那么您可以旋转一下。

The URL of a hyperlink is contained in the href attribute, not the url attribute. 超链接的URL包含在href属性中,而不是url属性中。

You should also prevent the default action, making your code look like this: 您还应该阻止默认操作,使您的代码如下所示:

$('p.tweet a').click(function(event){
    var link = $(this).attr('url');
    $('iframe').attr('src',link);
    // cancel default event
    event.preventDefault();
});

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

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