从点击的td-tag中获取文本

时间:2013-12-30 09:42:26

标签: javascript jquery dreamweaver

我已经暂时停留在这段代码上了一段时间。在我点击一个数字字体大小为文本的td元素之后,我只想要一个增加大小的短语。

jQuery代码:

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

表:

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

alert-statement返回给我的唯一内容是“undefined”。如果我使用.text()或.value()(这是有道理的),我也无法工作。

5 个答案:

答案 0 :(得分:3)

this不应该在quotes中,将this放在引号中意味着您要查找标记类型this,还需要定义标识为{{{的元素1}}。在大小之后追加“px”以更改字体。

<强> Live Demo

更改

tekstPreview

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

您的代码将是

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

答案 1 :(得分:1)

应该是

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

答案 2 :(得分:0)

更改 $(this) $('this')

您正在尝试将字符串转换为jQuery对象而不是javascript对象。

DEMO HERE

答案 3 :(得分:0)

尝试

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

DEMO

答案 4 :(得分:0)

尽管我讨厌淹没在一片有效的答案之中,但这一点很特别:

Demo Fiddle

jQuery的:

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

而不是你的#tekstPreview我只是将每个数字改为自己的大小以用于概念验证。

相关问题