首页 > 解决方案 > 从元素/标签获取 ID

问题描述

这是一个给定的例子:

<textarea style="width:300px" id="xxx_001" name="xxx_001"></textarea>

我想获取 ID 的值

“xxx_001”

这是我的代码:

$('.buttonclick').on('click', function() {

    var textareaval = $('#textareavalue').val();

    $("tbody").find("tr").each(function() { //get all rows in table

        var ratingTdText = $(this).find('td.selected'); // where in one column is selected

        // this is what i get textarea tag/element see above
        console.log("ratingTdText html(): "+ratingTdText.html() );  

        // i want to get only xxx_001
        console.log("ratingTdText only id: "+ratingTdText.attr('id') ); // doesn't happen
        console.log("ratingTdText only id: "+ratingTdText.prop('id') ); // doesn't happen

        var only_id = ratingTdText.attr('id');

        $("#textareaset_"+only_id).text(textareaval);
        $('#checkboxset_' + only_id).prop('checked', true);
        $('#selectoptionset_'+only_id).val('1');
    });
});

请问,有解决办法吗?

这是一些输出:

console.log("ratingTdText: "+ratingTdText );

ratingTdText:[对象对象]

console.log("ratingTdText html(): "+ratingTdText.html() );  

ratingTdText html(): textarea style="width:300px" id="xxx_001 name="xxx_001">

console.log("ratingTdText only id attr(): "+ratingTdText.attr('id') );

仅 ratingTdText id attr():未定义

        console.log("ratingTdText only id prop(): "+ratingTdText.prop('id') );

ratingTdText 仅 id prop():

标签: htmlhtml-tabledatatableprop

解决方案


$('.buttonclick').on('click', function() {

var textareaval = $('#textareavalue').val();

$("tbody").find("tr").each(function() { //get all rows in table

    var ratingTdText = $(this).find('td.selected'); // where in one column is selected

    // this is what i get textarea tag/element see above
    console.log("ratingTdText html(): "+ratingTdText.html() );  

    // i want to get only xxx_001
    console.log("ratingTdText only id: "+ratingTdText.attr(this) ); // doesn't happen
    console.log("ratingTdText only id: "+ratingTdText.prop(this) ); // doesn't happen

    var only_id = ratingTdText.attr('id');

    $("#textareaset_"+only_id).text(textareaval);
    $('#checkboxset_' + only_id).prop('checked', true);
    $('#selectoptionset_'+only_id).val('1');
});

});

相反 od using id 尝试使用它可能会起作用


推荐阅读