jQuery 使用 ID 作为 URL 选择一个项目

jQuery select an item using ID that is an URL

本文关键字:一个 项目 选择 使用 ID 作为 URL jQuery      更新时间:2023-09-26

我有一个div元素(复选框),其URL使用如ID...

id="http://www.mypage.com/page1"

然后我得到了一个变量,其中有链接

var temp = "http://www.mypage.com/page1"

当我称之为:

$("#"+temp).trigger('click');

我收到错误:

未捕获错误:语法错误,无法识别的表达式:#http://www.mypage.com/page1

有什么想法吗?

Aa @cristian上面提到的,你不能使用 url 作为 id,除非你删除它的所有特殊字符。您可以做的是,1) 从 ID 中删除 spl 字符,以便 ID 可用。2) 设置 jQuery 数据作为您的 URL。这是我的工作,虽然有点丑陋,但有效。

var temp = "http://www.mypage.com/page1";
//Create an id from 'temp' removing all spl chars.
var tempID = temp.replace(/[^a-z0-9-_]+/gi, "");
//Find all IDs starting with http
$("[id^='http']").filter(function() {
    //Set data from the ID (URL)
    $(this).data("ele-path", this.id);
    //Change the id removing all spl chars.
    this.id = this.id.replace(/[^a-z0-9-_]+/gi, "");
});
$(document).on("click", "#" + tempID, function() {
    alert ("click");
    //Get the URL from data
    alert( $(this).data("elePath") );
});