【问题标题】:jQuery: can't select linkjQuery:无法选择链接
【发布时间】:2012-07-15 23:34:08
【问题描述】:

我正在尝试在我正在开发的自定义插件中使用 wordpress 的媒体上传弹出窗口。

到目前为止一切正常,我能够上传图像并将它们插入到一个字段中,但我还有另一个字段需要指向已上传 pdf 的链接。

tb_show('', 'media-upload.php?type=image&TB_iframe=true;height=200');
window.send_to_editor = function(html) {
    console.log(html);

    console.log(jQuery('a', html));
    console.log(jQuery('a', html).attr('href'));

    console.log(jQuery('img', html));
    console.log(jQuery('img', html).attr('src'));

    imgurl = jQuery('a', html).attr('href');
    current_upload.prev().val(imgurl);

    tb_remove();
}

对于图像,这将是我的输出,这是正确的,因为它能够选择图像源

<a href="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM.png"><img src="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt="" title="Screen Shot 2012-06-20 at 12.15.52 PM" width="300" height="221" class="alignnone size-medium wp-image-49" /></a> to.js:54
[]
undefined
[
    <img src=​"http:​/​/​to.local/​wp-content/​uploads/​2012/​07/​Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt title=​"Screen Shot 2012-06-20 at 12.15.52 PM" width=​"300" height=​"221" class=​"alignnone size-medium wp-image-49">​
]
http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png 

但是当我选择 PDF 时,我得到了这个:

<a href='http://to.local/wp-content/uploads/2012/07/01-Mobile-Characteristics-and-Interaction-Design-Principles-Slides2.pdf'>01 Mobile Characteristics and Interaction Design Principles (Slides)</a> to.js:54
[]
undefined
[]
undefined 

所以我不明白为什么 jQuery('img', html) 可以正常工作而 jQuery('a', html) 不能正常工作,而在这两种情况下,返回的 html 中都有一个链接。

【问题讨论】:

    标签: jquery wordpress upload media


    【解决方案1】:

    html 本身就是一个“a”。

    console.log(jQuery(html).attr('href'));
    

    【讨论】:

      【解决方案2】:

      假设html = jQuery('&lt;a href="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM.png"&gt;&lt;img src="http://to.local/wp-content/uploads/2012/07/Screen-Shot-2012-06-20-at-12.15.52-PM-300x221.png" alt="" title="Screen Shot 2012-06-20 at 12.15.52 PM" width="300" height="221" class="alignnone size-medium wp-image-49" /&gt;&lt;/a&gt;');, html &lt;a&gt; 元素。

      jQuery('a', html) 尝试在html 的子代中选择&lt;a&gt;,由于那里没有&lt;a&gt; 元素,因此不返回任何结果。

      由于&lt;img&gt;html&lt;a&gt; 父级的子级,因此jQuery('img', html) 有效。

      在您的情况下,要获取htmlhref 属性,请执行以下操作:

      jQuery(html).attr("href")
      

      (如果html已经是一个jQuery对象,则删除jQuery()

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-26
      • 2010-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      相关资源
      最近更新 更多