通过innerHTML查找元素以从注入的javascript中调用角度ng-click

时间:2019-03-28 11:16:11

标签: javascript angularjs

我正在尝试通过注入的脚本从网页上的特定a-tag调用 ng-click

如何从页面中找到确切的A标签?我知道我是否有一个可以写($('a.classname'))的类名,但是有一种方法可以找到包含innerHTML Apple

如果不是,是否可以调用ng-click,因为它是页面上的第10个a-tag?作为[10]?

页面上的标签:

    <a ng-click="myFunction()">Apple</a>

已注入脚本:

    angular.element($('a')).scope().$apply(function() {
    angular.element($('a')).scope().myFunction();
    });

2 个答案:

答案 0 :(得分:2)

如果您尝试从外部(例如在扩展程序中或从控制台)执行此操作,则可以在目标元素上触发click事件。

您可以使用eq()来定位<a>的索引,也可以使用:contains选择器,或者使用filter()

来进行更精细的文本测试

angular
  .module('app', [])
  .controller('MainCtrl', ($scope) => {
    $scope.myFunc = (val) => {
      console.log('Clicked value = ', val)
    };
  });

// from outside angular app
setTimeout(() => {
  // by index
  $('a').eq(3).click()
  // or by text contains
  $('a:contains(Apple)').click();
  // using filter()
  $('a').filter(function() {
    return this.textContent.trim() === 'Apple';
  }).click();

}, 500)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.js"></script>

<div ng-app="app" ng-controller="MainCtrl">
  <a href ng-click="myFunc(1)">1</a>
  <a href ng-click="myFunc(2)">2</a>
  <a href ng-click="myFunc(3)">3</a>
  <a href ng-click="myFunc(4)">Apple</a>
</div>

答案 1 :(得分:0)

关于我对charlietfl的回答中关于xpath的评论,以为我也将分享我所引用的示例。

// by specific anchor tag from full xpath

var nodesSnapshot = document.evaluate("//html/body/div[1]/a[1]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
{
nodesSnapshot.snapshotItem(i).click();
nodesSnapshot.snapshotItem(i).style.background = 'yellow';
console.log('Clicked first <' + nodesSnapshot.snapshotItem(i).tagName + '> tag and marked it yellow')
}

// or by specific anchor tag from xpath by index that contains the text

var nodesSnapshot = document.evaluate("//a[3][text()[contains(., 'Apple')]]", document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null );
for ( var i=0 ; i < nodesSnapshot.snapshotLength; i++ )
{
nodesSnapshot.snapshotItem(i).click();
nodesSnapshot.snapshotItem(i).style.background = 'pink';
console.log('Clicked third <' + nodesSnapshot.snapshotItem(i).tagName + '> tag that contains ' + nodesSnapshot.snapshotItem(i).text + ' and marked it pink')
}
<div ng-app="app" ng-controller="MainCtrl">
  <text>1: </text><a ng-click="myFunction()">Apple</a>
  <text>2: </text><a ng-click="myFunction()">Apple</a>
  <text>3: </text><a ng-click="myFunction()">Apple</a>
</div>