gpt4 book ai didi

javascript - 如何通过#ID 100% AngularJS 获取元素 SELECT 中的文本和值

转载 作者:行者123 更新时间:2023-11-28 02:58:43 25 4
gpt4 key购买 nike

AngularJS 有更好的方法,代码行数比我的例子少..?我们的想法是使用 AngularJS 和 jqLit​​e 使其 100% 成为现实。

链接示例我的代码解决方案: http://jsfiddle.net/EOM/xecymL9t/

HTML:

<div data-ng-controller="Main" data-ng-app>

<select id="yo" data-ng-model="selection" data-ng-change="sample(selection)" required="required">
<option value="11" selected="selected">Name 2</option>
<option value="10">Name 1</option>
<option value="">SELECT DEFAULT ANGULAR INIT</option>
<option value="12">Name 3</option>
</select>

在浏览器的控制台中查看显示 (F12)

AngularJS:

function Main($scope, $document) {

$scope.sample = function(myvalue) {
// Get By ID
var e = $document[0].getElementById('yo');
// Get all options select
e = angular.element(e).find('option');
// Loop
angular.forEach(e, function(v, k){
// Is option selected..?
if(angular.element(v).prop('selected')){
// Get Text option selected
console.log('Text: '+angular.element(v).text()); // Text
}
});
console.log('Value: '+myvalue) // Value
}}

最佳答案

这个有点短,但我不知道你是否认为它是 100% AngularJS + jqLit​​e。 AngularJS docs假设您应该使用标准 DOM API 进行高级查询(jqLit​​e 的 find 仅限于按标签名称查找)

function Main($scope, $document) {

$scope.sample = function(myvalue) {
var e = $document[0].getElementById('yo')
.querySelector('[value="' + myvalue + '"]');

// Get Text option selected
console.log('Text: '+angular.element(e).text()); // Text
console.log('Value: '+myvalue) // Value
}
}

您可以查看解决方案here

关于javascript - 如何通过#ID 100% AngularJS 获取元素 SELECT 中的文本和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35604956/

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