【问题标题】:How can I access a property of an html element?如何访问 html 元素的属性?
【发布时间】:2017-11-14 02:03:34
【问题描述】:

我正在尝试获取 HTML 元素的 "validacion" 属性。

console.log (element[0]);

这会返回我:

<input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text" validacion="required">

如何访问"validacion" 属性?

【问题讨论】:

  • element.attr('validacion')。见docs.angularjs.org/api/ng/function/…
  • console.log(element[0].getAttribute("validacion"));
  • @DannyFardyJhonstonBermúdez 它有效!你能把它作为答案吗?
  • @yavg 见我回答。如果您需要更多详细信息,请随时询问。 :)
  • 仅供参考,属性与属性不同。见*.com/questions/19246714/…

标签: javascript dom


【解决方案1】:

你需要Element.getAttribute()方法:

console.log(element[0].getAttribute("validacion"));

【讨论】:

    【解决方案2】:

    试试element[0].attributes['validacion'].value

    祝你有美好的一天!

    【讨论】:

      【解决方案3】:

      不知道为什么需要这样做:

      你最好使用指令的方式来获取元素。

      或者你可以使用 Angular jqLite API:

      angular.element('#asunto').attr('validacion')
      

      【讨论】:

        【解决方案4】:

        我认为这就是您正在寻找的答案。

        既然您使用的是Angular 并且您正在实现ng-model="asunto",为什么不在html 中这样写。

        <input class="estilo_input_text ng-pristine ng-untouched ng-valid ng-empty" id="asunto" name="asunto" ng-model="asunto" placeholder="Asunto" type="text">
        
        <button ng-click="get_model(asunto)"></button>
        

        在你的 JS 中:

        $scope.asunto = "model";
        
        $scope.get_model = function (string) {
          console.log(string)
        }
        

        我认为这可能会起作用,因为您已经在使用 ng-model 为什么不使用 ng-model 代替。

        【讨论】:

          【解决方案5】:

          您可以简单地使用 getAttribute

          console.log(element[0].getAttribute("validacion"));
          

          【讨论】:

            【解决方案6】:

            使用element[0].getAttribute("attribute_name"); 方法。

            【讨论】:

            • element 是一个 jqLit​​e 对象(或数组),不会有 getAttribute 方法
            • 已更正,但即使查询返回单个项目数组,命名约定也规定变量的名称应命名为“元素”
            • @SujalMandal 你应该将element[0].getAttribute("attribute_name "); 更改为element[0].getAttribute("attribute_name");
            最近更新 更多