簡體   English   中英

使用javascript模擬javascript上的點擊事件:href

[英]Use javascript to simulate a click event on javascript: href

我正在使用允許我們添加自定義 javascript 的 3rd 方系統,我需要一種方法來查找自定義 URL,然后讓系統彈出用戶登錄名,該登錄名通過單擊 href="javascript:;" 調用

< a class="nav-link" href="javascript:;"> < b>sign in</b></ a>

注意 class="nav-link" 不是唯一的

我在尋找自定義 URL 並執行各種操作時沒有問題,但我不知道如何在該 javascript href 上執行模擬點擊事件,以便它彈出用戶登錄名。

例如登陸:“https://our.site.com/webstoreNew/services/guestprofile” 自定義 URL 部分是“guestprofile”,它不會被主系統重定向並保持不變

我嘗試了以下方法:

<script>
const guest_url = "https://our.site.com/webstoreNew/services/guestprofile";
let current_url = window.location.href;


if(current_url === guest_url) {

$('href="javascript:;"')[0].click();
}

</script>

其他嘗試:

$(javascript:;)[0].click();
$(href="javascript:;")[0].click();

我覺得這可能是一個語法問題,但需要有人的幫助

編輯:更新了更多代碼並刪除了可以在代碼段中使用的代碼。

檢查下面的代碼片段,只需創建一個函數並像下面的示例中一樣調用它fakeClick(); .

如果你想定位你提到的 href,你可以像這樣使用querySelector

const href = document.querySelector('[href="javascript:;"]');

下面的代碼段不會觸發點擊,因為我們使用的是window.location.href; stackoverflow 片段中不支持它。 話雖如此,如果您在項目中運行它,它將按預期運行。

 //your guest url const guest_url = "https://our.site.com/webstoreNew/services/guestprofile"; let current_url = window.location.href; //this is the a element where we trigger the click const href = document.querySelector('[href="javascript:;"]'); console.log(href); //this is the function //if both are equal it will trigger a click on atag function fakeClick() { if(current_url === guest_url) { href.click(); } } //here we are calling the function so it will run immediately fakeClick();
 <a class="nav-link" href="javascript:;"><b>sign in</b></a>

此外,正如@Oskar Grosser 提到的,如果您想使用示例中的代碼,您只需要更改不正確的調用:

$('href="javascript:;"')[0].click();
}

對此:

$('[href="javascript:;"]')[0].click();
}

如您所見,調整后的 Jquery 與 querySelector 調用相匹配,並且應該以相同的方式運行。

使用 jQuery,您可以使用CSS Selectors查詢一個或多個元素。

由於要查詢確切的屬性,因此必須像這樣設置查詢字符串的格式:
[attributeName="value"]

另一個注意事項是,您查詢的內容必須在字符串中。 通過您的其他嘗試,瀏覽器會嘗試將javascripthref解析為變量,因此會出現錯誤。

click()本身的調用是正確的,它將觸發一個點擊事件。

 // Setup for feedback; ignore $("a").click(() => console.log("'a' was clicked!")); // Correct query $('[href="javascript:;"]').click();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <a href="javascript:;">A link</a>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM