简体   繁体   English

jQuery - console.log()返回一个元素,但我无法访问它

[英]jQuery - console.log() returns an element but I can't access it

I happened to have super dumb issue and I'm stuck. 我碰巧有一个超级愚蠢的问题而且我被卡住了。

I do console.log(data) and I get exactly this: 我做console.log(数据),我得到了这个:

<a href='http://www.someurl.com'>caption</a> 

The question is how do I get this links "href" attribute. 问题是如何获得此链接“href”属性。

I have absolutely no idea why, but these doesn't work: 我完全不知道为什么,但这些不起作用:

data.text() == Uncaught TypeError: undefined is not a function (should be: caption) data.text() == Uncaught TypeError:undefined不是函数(应该是:caption)

$('a',data).attr('href') == undefined (should be: http://www.someurl.com ) $('a',data).attr('href') == undefined(应该是: http//www.someurl.com

Maybe this is not a string, but object or something else? 也许这不是一个字符串,而是对象或其他东西? How to check that? 怎么检查? My JS looks like this: 我的JS看起来像这样:

 window.send_to_editor = function(data) {
      var videourl = data;
      console.log(videourl.text()); // Uncaught TypeError: undefined is not a function
      console.log(videourl);  // <a href='http://www.someurl.com'>caption</a>
    }

Using jQuery, you can do something like that: 使用jQuery,你可以做类似的事情:

var data = "<a href='http://www.someurl.com'>caption</a>";
var link = $(data).attr('href'); 

It will create dynamically your DOM element, then you will be able to get your attribute href. 它将动态创建您的DOM元素,然后您就可以获得属性href。

You should first find out, what type data is. 您应该首先找出data类型。 To do this you can use the JavaScript builtin function typeof(data) . 为此,您可以使用JavaScript内置函数typeof(data)

It's not a jQuery object. 它不是一个jQuery对象。 That is why it is undefined. 这就是它未定义的原因。 First, create a jQuery object . 首先, 创建一个jQuery对象

var _videourl = $(videourl);
console.log(_videourl.text());
console.log(_videourl.attr('href'));
// caption (index)
// http://www.someurl.com 

DEMO

In your case, data is a string, not a jQuery object and therefore does not have of jQuery's methods (like text ). 在您的情况下,数据是一个字符串,而不是一个jQuery对象,因此没有jQuery的方法(如text )。

If you are certain that data is a string containing a link, you can use a regular expression to extract the link like so: 如果您确定data是包含链接的字符串,则可以使用正则表达式来提取链接,如下所示:

var match = data.match(/href='(.*)'/g);
url = match && match[1];
console.log(url);

Alternately, you can create a jQuery object from your string. 或者,您可以从字符串创建jQuery对象。 But that's a much more expensive operation if you just want to get the url. 但是,如果你只是想获得网址,这是一个更昂贵的操作。

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

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