如何通过类名或 id 获取元素 [英] How to get element by classname or id
问题描述
我正在尝试通过 angularjs 在 html 中查找元素.
I am trying to find the element in html by angularjs.
这是html:
<button class="btn btn-primary multi-files" type="button">
<span>Choose multiple files</span>
</button>
<br/><br/>
<input ng-file-select type="file" multiple style="display: none"/><br/>
我试图通过类名多文件获取按钮元素,然后我尝试了
I am trying to get the button element by class name multi-files, then I tried
var multibutton = angular.element(element.getElementsByClassName(".multi-files"));
但它不起作用,并尝试了 element.find
但它仅适用于标记.
But it does not work, and tried element.find
but it only works for tag.
angularjs 中是否有可以通过 id 或 classname 获取元素的函数?
Is there any function that can get element by id or classname in angularjs?
推荐答案
getElementsByClassName
是 DOM 文档上的一个函数.它既不是 jQuery 也不是 jqLite 函数.
getElementsByClassName
is a function on the DOM Document. It is neither a jQuery nor a jqLite function.
使用时不要在类名前加句点:
Don't add the period before the class name when using it:
var result = document.getElementsByClassName("multi-files");
将其包裹在 jqLite 中(如果 jQuery 在 Angular 之前加载,则使用 jQuery):
Wrap it in jqLite (or jQuery if jQuery is loaded before Angular):
var wrappedResult = angular.element(result);
如果您想从指令链接函数中的 element
中进行选择,您需要访问 DOM 引用而不是 jqLite 引用 - element[0]
而不是元素
:
If you want to select from the element
in a directive's link function you need to access the DOM reference instead of the the jqLite reference - element[0]
instead of element
:
link: function (scope, element, attrs) {
var elementResult = element[0].getElementsByClassName('multi-files');
}
或者你可以使用document.querySelector
函数(如果按类选择,这里需要句号):
Alternatively you can use the document.querySelector
function (need the period here if selecting by class):
var queryResult = element[0].querySelector('.multi-files');
var wrappedQueryResult = angular.element(queryResult);
演示: http://plnkr.co/edit/AOvO47ebEvrtpXeIzYOH?p=预览
这篇关于如何通过类名或 id 获取元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!