You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:页面加载时自动点击所有文本为‘add as friend’的a标签

Hey there! Let's get this sorted for you—here's how to automatically trigger clicks on all <a> tags with the exact text "add as friend" while stopping any unwanted page navigation or frame loads:

$(document).ready(function () {
  // Target only links with the exact text "add as friend" (trim handles extra whitespace)
  $("a").filter(function() {
    return $(this).text().trim() === 'add as friend';
  }).each(function () {
    // First, add a click handler to block default navigation behavior
    $(this).on('click', function(e) {
      e.preventDefault(); // Stops the href from loading
      e.stopPropagation(); // Optional: prevents event bubbling up the DOM
    });
    
    // Now trigger the click event on the link
    $(this).click();
  });
});

Breakdown of the Fix:

  • Exact Text Matching: Using filter() instead of just :contains() ensures we don't accidentally target links that only include "add as friend" as part of longer text. The .trim() handles any accidental spaces around the link text.
  • Prevent Default Behavior: The click handler with e.preventDefault() is critical—it stops the browser from following the href or opening the target frame, which is exactly what you wanted to avoid.
  • No ID Needed: We're targeting elements purely by their text content, so you don't have to add any extra IDs or attributes to your links.

Simplified Alternative (If You Want Less Code):

If all you need is to trigger the click and block navigation, you can combine the steps like this:

$(document).ready(function () {
  $("a").filter(function() {
    return $(this).text().trim() === 'add as friend';
  }).each(function() {
    $(this).trigger('click');
  });
});

// Global handler to block navigation for these specific links
$(document).on('click', 'a', function(e) {
  if ($(this).text().trim() === 'add as friend') {
    e.preventDefault();
  }
});

Why Your Original Code Wasn't Working:

You were missing the key step of preventing the default anchor behavior. Without e.preventDefault(), even when you triggered the click, the browser would still try to load the URL in the target frame—this fix stops that from happening.

内容的提问来源于stack exchange,提问作者ajay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:07:18