如何使用变量选择器的输入变量使用jquery读取属性?

时间:2013-01-16 02:33:14

标签: javascript jquery html

我想重新加载一个特定的div,它的id对应于一个表元素的id ...(div只有一个表子)。

警告说tID未定义。

的javascript:

function (msg) {
         var tID = $("table", msg).attr('id');
         alert(tID);
         $("#reloadme_"+tID).html(msg);
}

HTML:

 <div id="reloadme_2036">

        <table id="2036"  class="customCSSclass">
            ...table contents...
        </table>

   </div>

我哪里出错?

3 个答案:

答案 0 :(得分:3)

find查找jQuery对象中当前元素集的后代,您应该使用.filter来过滤jQuery对象本身中的元素:

$('<table id="001">[...]</table>')
//the jQuery object will contain a reference to the parsed <table> element,
//so you have to .filter() the jQuery object itself to extract it

当然,如果它是jQuery对象中唯一的元素,则不需要进行过滤。 =]

此外,您还可以.find使用tr。查找jQuery对象内引用的td元素后代的table / {{1}}(或任何其他元素)。

答案 1 :(得分:1)

也许这就是你要找的东西?

function reload(msg) {
  var tID = msg.match(/id="(\d{1,4})"/i)[1]; //find 1 to 4 digits in the id attribute
  alert(tID);  //alerts 2036
  $("#reloadme_"+tID).html(msg); //adds the content to the div
}
reload('<table id="2036" class="customCSSclass"> ...table contents... </table>');

如果是这样,你可能正在寻找的是javascript的.match()方法,它会在字符串中找到id号。

查看JSFiddle

答案 2 :(得分:0)

你必须尝试这样

var msg='<table id="2036"  class="customCSSclass"></table>';
alert($(msg).attr("id"));