gpt4 book ai didi

javascript - 如何使用 ng-click 获取 DOM 元素

转载 作者:行者123 更新时间:2023-11-29 16:06:59 26 4
gpt4 key购买 nike

我有一些元素,比如:

<button ng-click="weirdFunction()">Pretty Button</button>

Controller 中的功能:

$scope.weirdFunction = function(element) {
console.log(element);
}

在控制台日志中我想接收这个 DOM 元素。我尝试通过多种方式做到这一点:

  1. <button ng-click="weirdFunction()" ng-model="button">Pretty Button</button>

    $scope.weirdFunction = function() {
    console.log($scope.button);
    }

  2. <button ng-click="weirdFunction(button)" ng-model="button">Pretty Button</button> $scope.weirdFunction = function(elem) {
    console.log(elem);
    }

  3. <button ng-click="weirdFunction($element)">Pretty Button</button> $scope.weirdFunction = function(elem) {
    console.log(elem);
    }
    但所有的尝试都以失败告终。我哪里错了?如何获取点击的元素?

最佳答案

请尝试以下代码段。

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.weirdFunction = function(element) {
console.log(element);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<button ng-click="weirdFunction($event.currentTarget)">Pretty Button</button>
</div>

关于javascript - 如何使用 ng-click 获取 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38914643/

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