解析id-Javascript的url
我正在尝试实现以下功能:解析id-Javascript的url,javascript,jquery,html,Javascript,Jquery,Html,我正在尝试实现以下功能: function destroy_clusters() { // returns the link var link = document.getElementById("destroy").href; return false; } 当单击以下单击时将触发: <a href="http://127.0.0.1:8000/clusters/show/destroy_clusters/33/" onclick="return destroy
function destroy_clusters() {
// returns the link
var link = document.getElementById("destroy").href;
return false;
}
当单击以下单击时将触发:
<a href="http://127.0.0.1:8000/clusters/show/destroy_clusters/33/" onclick="return destroy_clusters();></a>
我需要解析该链接以获取id值(在这种情况下,33
)。问题是,我甚至不知道从哪里开始。。。
url始终具有相同的模式。我们唯一需要注意的是,如果id未定义或为空。。。这将是有用的 您可以将其作为参数传递,而不是解析任何内容:
function destroy_clusters(id) {
// use the id here
}
尝试以下操作:
$(function(){
$('a').click(function(e) {
e.preventDefault();
alert("ID" + $(this).data('id'));
return false;
});
});
演示:
html:
使用javascript拆分来分解url并返回最后一部分。 在此处查看JSFIDLE: Javascript
function destroy_clusters(elem) {
var link = elem.href;
var splitlink = link.split("/");
alert(splitlink[splitlink.length-2]);
}
HTML
url是否总是具有相同的模式?那么,“destroy_clusters/”总是在id之前吗?嗯getElementById
但是您将它标记为jQuery。我很困惑链接是由Django创建的<代码>。首先我试着按照你说的做。。。但是我错过了如何将cluster.id
传递给函数调用
function parseId(href) {
var match = href.macth(/\/(\d+)\/?$/);
return match && match[1];
}
function getId() {
var link = document.getElementById("destroy").href;
return = parseId(link);
}
function destroy_clusters(elem) {
var link = elem.href;
var splitlink = link.split("/");
alert(splitlink[splitlink.length-2]);
}
<a href="http://127.0.0.1:8000/clusters/show/destroy_clusters/33/" onclick="destroy_clusters(this);">Click Me</a>