尝试从 js this 关键字中提取字符串

trying to extract a string from a js this keyword

本文关键字:提取 字符串 关键字 this js      更新时间:2023-09-26

我正在尝试在加载链接之前单击链接后执行javascript,使用以下代码:

$('body').on("click", 'a', function (evt) {
            evt.preventDefault();
            console.log(this);
            $('.content').addClass('hide');
            if (this.search("AV") > 0) {
                $('#AVheader').addClass('fullwidth');
            }
            setTimeout(function () {
                window.open(this, "_self");
            }, 500);
        });

我的错误是:

this.search 不是函数和

window.open(this, "_self");不起作用

想把问题放在那里,因为我找不到一个简单的解释,我可能会花半天的时间试图弄清楚它。

当您在事件处理程序中时,this指向单击的链接。元素没有search方法。可能您正在尝试在链接中的某处搜索字符串,也许是内容。

    $('body').on("click", 'a', function (evt) {
        evt.preventDefault();
        console.log(this);
        $('.content').addClass('hide');
        if (this.innerHTML.search("AV") > 0) {
            $('#AVheader').addClass('fullwidth');
        }
        setTimeout(function () {
            window.open(this.href, "_self");
        }.bind(this), 500);
    });
超时

函数中的this不会引用您的锚元素,而是引用全局window对象。您需要保存对该元素的引用,然后在超时回调中使用该引用

$('body').on("click", 'a', function (evt) {
  evt.preventDefault();
  //save the "this" reference
  var that = this;
  $('.content').addClass('hide');
  if (this.search.search("AV") > 0) {
    $('#AVheader').addClass('fullwidth');
  }
  setTimeout(function () {
    window.open(that.search, "_self");
  }, 500);
});

此外.search锚元素上的属性不是一个函数,而是一个字符串,你必须执行this.search.search("AV")this.href.search("AV"),具体取决于您实际尝试搜索的内容