gpt4 book ai didi

javascript - 动态添加特定属性到元素

转载 作者:行者123 更新时间:2023-11-29 21:26:58 25 4
gpt4 key购买 nike

我使用 Angular Directive(指令)创建了 valid-file 属性,因为文件输入(使用 bootstrap filestyle plugin )看不到 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 属性。如果我使用$("输入").attr("有效文件");什么都不会改变。如果我使用 $("input").attr("valid-file",true); 它会添加属性 valid-file="true" 但验证会中断.你能给我一些建议吗?这是 plunker http://plnkr.co/edit/Gcbb7r05VBTjbh9x5Ma8?p=preview

最佳答案

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

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

因为只有$("input").attr("valid-file")用于获取属性“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>

关于javascript - 动态添加特定属性到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37251468/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com