简体   繁体   English

jQuery中的这段代码有什么问题

[英]What is wrong with this code in jquery

I am trying to get plain text out of value stored in variable like this 我试图从这样的变量中存储的值中获取纯文本

var lb = $(this).attr("htmllabel");
var text = $(this).html(lb);
alert(text);

When the alert popup it give result as object[Object] but I was expecting the actual string after application of the function. 当警报弹出时,它给出的结果为object [Object],但我期望在应用该函数后得到实际的字符串。

Can anyone help me in this? 有人可以帮我吗? Thanks. 谢谢。

$(this).html(lb)

This line is setting the html of whatever this is to whatever is stored in lb . 这条线被设置 HTML什么的this是无论是存储在lb It then returns the jquery object for chaining purposes. 然后,它出于链接目的返回jquery对象。

If you want the html of this then you just call $(this).html() with no parameter. 如果你想在htmlthis ,那么你只需要调用$(this).html()不带参数。

Your code on the second line is setting something not getting something ... 您在第二行上的代码设置了一些无法得到的东西...

Can you include your HTML and the actual data you want in the alert box and this might help shape the answer 您能否在警报框中包含HTML和所需的实际数据,这可能有助于确定答案

Take a look at the documentation for the html method: 查看html方法的文档:

http://api.jquery.com/html/#html2 http://api.jquery.com/html/#html2

As you can see from the documentation your code is setting the html for this and then returning a jQuery object. 从文档中可以看到,您的代码this设置了html,然后返回了jQuery对象。 What is it that you want to display exactly? 您要确切显示什么?

If you're simply looking to get the value of your custom attribute "htmllabel", you can do the following: 如果您只是想获取自定义属性“ htmllabel”的值,则可以执行以下操作:

var val = $(this).attr("htmllabel");
alter(val);

As a side note; 作为旁注; I would suggest naming custom attributes with data-* according to the HTML5 spec like this: 我建议根据HTML5规范使用data-*命名自定义属性,如下所示:

<div data-htmllable></div>

Your can then access the value of the attribute in two ways (jQuery 1.4.3+): 然后,您可以通过两种方式(jQuery 1.4.3+)访问属性的值:

var val1 = $(this).attr('data-htmllabel');
var val2 = $(this).data('htmllabel');

// Outputs same value //
alert(val1);
alert(val2);

I hope this helps! 我希望这有帮助!

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

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