简体   繁体   中英

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.

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 . It then returns the jquery object for chaining purposes.

If you want the html of this then you just call $(this).html() with no parameter.

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

Take a look at the documentation for the html method:

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. 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:

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:

<div data-htmllable></div>

Your can then access the value of the attribute in two ways (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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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