将特定属性动态添加到元素中

Dynamically add specific attr to element

本文关键字:元素 添加 动态 属性      更新时间:2023-09-26

我使用angular指令创建了valid-file属性,因为文件输入(使用引导文件样式插件)看不到required属性:

    .directive('validFile',function(){
        return {
            require:'ngModel',
            link:function(scope,el,attrs,ngModel){
                //change event is fired when file is selected
                el.bind('change',function(){
                    scope.$apply(function(){
                        ngModel.$setViewValue(el.val());
                        ngModel.$render();
                    })
                })
            }
        }
    })

我需要动态添加或删除valid-file属性。如果我使用$("input").attr("valid-file");什么都不会改变。如果我使用$("input").attr("valid-file",true);,它将添加属性valid-file="true",但验证将中断。你能给我一些建议吗?这是plunkerhttp://plnkr.co/edit/Gcbb7r05VBTjbh9x5Ma8?p=preview

如果要在任何元素中设置任何属性,则.attr()需要2个参数。

前任。$("input").attr("valid-file","");//空也可以..或任何值而不是空

因为只有$("input").attr("valid-file")用于获取属性"有效文件"的值

所以你需要.attr()中的2个参数来设置任何属性

试试这个:http://plnkr.co/edit/lSl3GdZrRAyFps5QOSlw?p=preview

 $("select").change(function(){
    if ($("select option:selected").val() == "0") {
      $("input").attr("valid-file",""); // try this
    } else {
      $("input").removeAttr("valid-file");
    }
  });

HTML:

<select name="" id="">
  <option value="">Select</option>
  <option value="0">Add attr
  <option value="1">Delete attr
</select>