【问题标题】:jQuery select an item using ID that is an URLjQuery使用作为URL的ID选择一个项目
【发布时间】:2015-05-09 20:18:36
【问题描述】:

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

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

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

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

当我这样称呼时:

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

我得到了错误:

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

有什么想法吗?

【问题讨论】:

  • 您必须转义所有特殊字符,例如 :.。在此处阅读更多信息learn.jquery.com/using-jquery-core/faq/…。这里的寓意是你不应该使用 url 作为 id。
  • 你可以使用更简单的id,如果你想传入url,你可以随时使用data-url="some_url"等数据属性传入...!

标签: javascript jquery checkbox jquery-selectors


【解决方案1】:

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

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") );
});

【讨论】:

  • 这很好,谢谢。但我正在将 id 值从 url 更改为“普通”id。
  • 该更改由脚本完成,如果您真的愿意,您可以继续将 URL 作为 ID。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-01
  • 2010-12-19
  • 1970-01-01
  • 2012-07-18
  • 2011-04-13
  • 2010-12-24
  • 2018-11-09
相关资源
最近更新 更多