【问题标题】:Test if the HTML attribute is present and get the value测试 HTML 属性是否存在并获取值
【发布时间】:2016-08-10 18:01:35
【问题描述】:

我正在尝试测试是否存在 HTML 属性并使用 has Attribute("tabindex") 属性获取值。但我收到以下错误:

无法获取未定义或空引用的属性“hasAttribute”

我正在使用 jGrid 和 jQuery。如果该属性存在,我将尝试获取该特定 td 的值。

请参考以下代码:

<tr class="jqgrow ui-row-ltr ui-widget-content  myAltRowClassEven ui-state-highlight" tabindex="0" id="2" role="row" aria-selected="true">
    <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight" style="text-align: left; height: 20px;" role="gridcell">
        TESTTHIS
    </td>
</tr>

【问题讨论】:

  • 如何选择 html 元素? Unable to get xxx of undefined 让我相信您对元素的引用可能存在问题
  • 您介意发布您的测试代码吗?如果我们能看到代码,就会更容易告诉你错误是什么。
  • 您将“jqgrid”作为问题的标签。如果您更清楚地表述问题将会很有帮助:您需要在哪里(在哪个回调中)测试某些属性的存在。包含 JavaScript 代码可以清除很多东西。

标签: javascript jquery html jqgrid


【解决方案1】:

试试这个:

$("#item").attr("tabindex")

【讨论】:

  • 这成功了。非常感谢大家的解决方案。
  • 谢谢。你能标记它有解决方案吗?
【解决方案2】:

使用 jQuery has attribute selector 过滤掉带有tabindex 属性的元素。

var text = $('td[tabindex]').text();
//--------------^^^^^^^^^^--------------------

【讨论】:

  • 嗨@Pranav。非常感谢您的建议。但问题是表处于循环中,并且有很多带有 tabindex 的 td。对不起,我忘了提到它在循环中。
  • @user3213490 [tabindex] 将有助于过滤掉 .... 例如:$('.yourclass[tabindex]')
【解决方案3】:

如果你想获取 tabindex 属性的值,你可以这样做:

$(function () {
  $('table tbody tr[tabindex]').each(function (i, e) {
    var tabindex = e.getAttribute('tabindex');
    console.log('tabindex=' + tabindex + ' Row text: ' + e.textContent);
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>

<table>
    <tbody>
    <tr class="jqgrow ui-row-ltr ui-widget-content  myAltRowClassEven ui-state-highlight" id="1" role="row"
        aria-selected="true">
        <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight"
            style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS
        </td>
    </tr>
    <tr class="jqgrow ui-row-ltr ui-widget-content  myAltRowClassEven ui-state-highlight" tabindex="0" id="2" role="row"
        aria-selected="true">
        <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight"
            style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS
        </td>
    </tr>
    <tr class="jqgrow ui-row-ltr ui-widget-content  myAltRowClassEven ui-state-highlight" tabindex="2" id="3" role="row"
        aria-selected="true">
        <td aria-describedby="jqGrid11_cname" title=" TESTTHIS" class="zeroBorderRight"
            style="text-align: left; height: 20px;" role="gridcell"> TESTTHIS
        </td>
    </tr>
    </tbody>
</table>

【讨论】:

    【解决方案4】:

    没有jquery,es6的解决方案

    var hasAttr = [...document.getElementById('#blah').attributes]
      .map(a => a.name)
      .indexOf(ATTRIBUTE) > -1;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-04
      • 1970-01-01
      • 2019-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      相关资源
      最近更新 更多