首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >失败:无法读取未定义的属性'element‘

失败:无法读取未定义的属性'element‘
EN

Stack Overflow用户
提问于 2018-05-31 23:13:19
回答 3查看 1.6K关注 0票数 1

需要从arryelement中找到元素的计数,如果count>1需要单击

代码语言:javascript
复制
/*search name is clinic name
clinicsearch is the arrayelement which has the list of clinic name list from the table*/
public SearchAndSelectClinicA(SearchName:string){
  this.ClinicSearch.sendKeys(SearchName);
  this.SearchIcon.click(); //click on the icon to get the clinic names
  this.SearchedClinic.count().then(function(count){
    //get the count of elements which are there in the Searchedclinic element array
    if(count>1){
      this.SearchedClinic.each(function(rows){ 
        /*Failed: Cannot read property 'SearchedClinic' of undefined 
          (Error gets displayed when it comes to above line.*/
        rows.getText().then(function(value){
          if(value.indexOf(SearchName)){
            //Click the element if the statement is satisfied
            rows.click();
          }
        });
      });
    }
  });
}

请帮我解决这个问题

失败:无法读取未定义的属性'SearchedClinic‘。

正在显示。

它能够执行到if语句。稍后,它会抛出上面指定的error,并立即停止执行

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-06-01 07:29:50

在JavaScript中,每个函数都有一个隐式的this。在嵌套函数情况下使用this时需要小心。

下图说明了这些this来自哪个函数。

第二个this.SearchedClinic将尝试访问属于嵌套函数thisfunction(count){},该函数没有名为SearchedClinic的属性。

您期望this指向上面的那个。因此,您需要将顶部的this赋给另一个变量,如下所示:

现在me指向最上面的this,你可以根据需要在任何嵌套函数中使用它。

票数 3
EN

Stack Overflow用户

发布于 2018-06-01 07:32:04

您的function(rows)将创建一个新的闭包。这意味着该作用域内的this不一定与外部的this相同。

以下是几个解决方案

  • 在上面定义了一个不同的变量,例如在函数内部使用的var self = this;

self.SearchedClinic`

  • Use使用相同作用域的ES6函数定义。

this.SearchedClinic.count().then((count) => {});

  • 使用.bind(this)

This.SearchedClinic.count()计数((function(.then) => { }).bind(this));

票数 1
EN

Stack Overflow用户

发布于 2018-06-02 08:02:18

假设有以下代码:

代码语言:javascript
复制
const result = obj1.printName.call(obj2);

在函数call下使用this将引用obj2,因为call()的第一个参数是显式设置this引用的内容。

这就是你所遇到的问题。

代码语言:javascript
复制
this.SearchedClinic.count().then(function(count){ 
    //calling this will reference the parameter count 
}

荣誉之间的任何this都将引用该函数的第一个参数。您要做的是声明一个全局变量:var searchedClinic = this.SearchedClinic。下面是更新后的代码:

代码语言:javascript
复制
public SearchAndSelectClinicA(SearchName:string){
  var searchedClinic = this.SearchedClinic;
  this.ClinicSearch.sendKeys(SearchName);
  this.SearchIcon.click(); //click on the icon to get the clinic names
  this.SearchedClinic.count().then(function(count){
    //get the count of elements which are there in the Searchedclinic element array
    if(count>1){
      searchedClinic.each(function(rows){ 
        rows.getText().then(function(value){
          if(value.indexOf(SearchName)){
            //Click the element if the statement is satisfied
            rows.click();
          }
        });
      });
    }
  });
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50627570

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档