为什么不是't我的更改事件启动

Why isn't my change event firing?

本文关键字:事件 启动 我的 为什么不      更新时间:2023-09-26

Title几乎解释了这一切。我举了一个w3学校的例子。

  <html>
  <head>
    <title>Example: Change event on a select</title>
    <script type="text/javascript">
      function changeEventHandler(event) {
        alert('You like ' + event.target.value + ' ice cream.');
      }
    </script>
   </head>
    <body>
        <label>Choose an ice cream flavor: </label>
        <select size="1" onchange="changeEventHandler(event);">
            <option>chocolate</option>
            <option>strawberry</option>
            <option>vanilla</option>
        </select>
    </body>
</html>

当我运行它时,警报框会运行。但是,当我运行代码时,我无法弹出警报框:

HTML

 <!DOCTYPE html>
<html lang="en-US">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="myCtrl.js"></script>
<body>
<div ng-app="myTestApp" ng-controller="myCtrl">
    <p>Looping with ng-repeat:</p>
    <label>Job Accounts</label>
    <select id="jobList" size="1" ng-model="selectedJobServer" onchange="myFunction()">
      <option ng-repeat="x in jobServers" value="{{x}}">{{x}}</option>
    </select> 
    <label>Oracle Accounts</label>
    <select ng-disabled={{isDisabled}} ng-model="selectedOracleServer">
      <option ng-repeat="x in oracleServers" value="{{x}}">{{x}}</option>
    </select>
    <p>The selected server is: {{selectedJobServer}}</p>
</div>
</body>
</html>

JS-

 var app = angular.module('myTestApp', []);
app.controller('myCtrl', function($scope) {
    $scope.isDisabled = true;
    $scope.jobServers = ['server1','server2','server3'];
    function myFunction(){
        alert("Hello! I am an alert box!");
    }
});

是否存在与angular的某些交互,从而引发问题?谢谢

您的函数应该在$scope中。

因此,您可以将myCtrl代码修改为

$scope.myFunction = function(){
   alert("Hello!");
}

此外,您还应该将事件从change修改为ng-change

<select id="jobList" size="1" ng-model="selectedJobServer" ng-change="myFunction()">
  <option ng-repeat="x in jobServers" value="{{x}}">{{x}}</option>
</select> 

如果使用angular,请使用angular。不要声明泛型函数,声明角度函数:

$scope.myFunction =  function (){
    alert("Hello! I am an alert box!");
}

不要使用onChange事件,使用ng-change:

 <select id="jobList" size="1" ng-model="selectedJobServer" ng-change="myFunction()">