gpt4 book ai didi

javascript - 相当于 hasAttribute() 的 AngularJS?

转载 作者:数据小太阳 更新时间:2023-10-29 05:07:35 26 4
gpt4 key购买 nike

在指令中,我想在对元素执行某些函数之前检查它是否具有属性。但我在 jqLite docs 中没有看到为此做的任何事情.

例如:

.directive('noReadonly', function() {

return {
link: function($scope, $element, $attr, ctrl) {

$element.on('focus', function() {
if ($element.hasAttribute('readonly'))
$element.removeAttr('readonly');
});

},
}
})

最佳答案

$attr 是一个具有属性的对象,因此您可以像平常一样使用它:

if($attr.hasOwnProperty("readonly"))

如评论中所述,这会检查该属性是否存在。此元素将导致真正的响应:

<input name="test" readonly>

如果你还想检查真值,你可以扩展逻辑:

if($attr.hasOwnProperty("readonly") && $attr.readonly) {}

请注意,属性值被解析为字符串,因此 $attr.readonly 等于 "true"(字符串)而不是 true( bool 值).

关于javascript - 相当于 hasAttribute() 的 AngularJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30266650/

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