简体   繁体   中英

Get text from clicked td-tag

I've been stuck on this piece of code for a while now. I just want a phrase to increase in size, after I click a td-element with the numeric font-size as text.

jQuery code:

$('td').click(function() {
        var string = $('this').html();
        alert(string);
        $('#tekstPreview').css("font-size", string);
        });

table:

<table border="0" cellspacing="10" id="table">


<tr>
    <td height="20" width="20">9</td>
    <td height="20" width="20">10</td>
    <td height="20" width="20">12</td>
    <td height="20" width="20">14</td>
    <td height="20" width="20">16</td>
    <td height="20" width="20">18</td>
    <td height="20" width="20">20</td>
  </tr>
</table>

The only thing the alert-statement returns me is "undefined". I doesn't work either if I use .text() or .value() (which makes sense).

The this should not be in quotes , putting this in quotes mean you are looking for tags type this , You also need to define element with id tekstPreview . Also append "px" after the size to have the font change.

Live Demo

Change

var string = $('this').html();

To

var string = $(this).html();

Your code would be

$('td').click(function () {
    var string = $(this).html();   
    $('#tekstPreview').css("font-size", string + "px");
});

It should be

$('td').click(function() {
    var string = $(this).html(); //change 'this' to this
    alert(string);
    $('#tekstPreview').css("font-size", string+"px"); // add px at the end
});

Change $(this) To $('this')

You are trying to convert string to jQuery object not the javascript object this.

DEMO HERE

Try with

$(this).html(); or $(this).text();

DEMO

As much as I hate drowning in a sea of answers that work, this one is made special:

Demo Fiddle

jQuery:

$('#table').on('click', 'td', function () {
    var string = $(this).text();
    $(this).css({fontSize: string+'px'});
});

Instead of your #tekstPreview I just made each number change its own size for proof-of-concept.

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