jQuery:无法选择链接

标签 jquery wordpress upload media

我正在尝试在我正在开发的自定义插件中使用 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 中都有一个链接。

最佳答案

假设html = jQuery('<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>'); , html <a>元素。

jQuery('a', html)尝试选择<a>html 的子级内,它不返回任何结果,因为没有 <a>那里的元素。

<img><a>的 child 父级 html , jQuery('img', html)有效。

就您而言,要获取 href html 的属性,执行此操作:

jQuery(html).attr("href")

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

关于jQuery:无法选择链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11515851/

相关文章:

php - Wordpress: fatal error 无法访问控制面板/管理面板

python - 如何将 Wordpress 放在 Heroku 上运行的 Flask 应用程序的/blog 目录中

linux - 使用curl上传图片

javascript - 如何创建 jquery 上一个和下一个按钮来遍历数组中的 URL(分页)

javascript - 如何在单击放置在 Iframe 内的 anchor 标记时执行 jQuery 函数

javascript - 如何更改饼图 Highcharts 中的字体属性?

mysql - 编辑页面更新问题 -> 覆盖超过应有的内容

jquery - Ajax post请求在wp主题目录中不起作用

php - Wordpress 插件 template_redirect 抛出 404

html - 上传前显示图片预览