单击网址时抓取网址参数.Jquery,Javascript

Grab URL parameter onclick of url.. Jquery, Javascript

本文关键字:Javascript Jquery 抓取 单击 参数      更新时间:2023-09-26

我在尝试存储使用 ajax post 响应创建的一些动态链接的 url 参数时遇到了一些问题。ajax 帖子工作正常,名称和子流派变量正在从 ajax 响应中正确填充。现在我想发生的是,用户点击其中一个生成的网址,网址内部的参数,即子类型="blah",将被发送到数据库并存储。我遇到的问题是标准事件单击功能无法在文档就绪功能的内部或外部工作。

$(document).ready(function() {

$.each(data, function() {
$('#artist-suggestions').append('<li><a href="http://...../100.php" artist="'+ this.name +'" subgenre="'+ this.subgenre +'" onclick="artistGen()">' + this.name +     this.new + '</a></li>');
});
});

然后我创建了一个 onclick 函数,如下所示,但我不能使用"this"查询,因为它超出了文档范围。我必须将onclick功能放在文档就绪功能之外,否则它将不起作用。

function artistGen(){
alert('dfdsf');
};

在这里错过了什么或我做错了什么?

您可以在

创建每个元素时在 onclick 函数中传递这些元素。

$(document).ready(function() {

$.each(data, function() {
  artist = this.name;
  $('#artist-suggestions').append('<li><a href="http://...../100.php" artist="'+ this.name +'"        subgenre="'+ this.subgenre +'" onclick="artistGen(' + this.Blah1 + ',' + this.Blah2' + ')">' + this.name +     this.new + '</a></li>');
});
})

;

function artistGen(Blah1, Blah2){
 saveData(Blah1, Blah2);
alert('dfdsf');
};

在 jQuery for dynamic 元素中,你可以这样使用 click 事件

$('#artist-suggestions li').on('click', 'a', function() {
    // do something
});

或者,您可以使用函数继续执行,但只需向该函数添加参数喜欢

function artistGen(Artist){
    // do something
};
您需要

.load()范围内删除artistGen()

函数
$(window).load(function(){    
  $('#artist-suggestions').append('<li><a href="http://...../100.php" artist="jim" subgenre="subgenre" onclick="artistGen()">jim new</a></li>');  
});
function artistGen(){
  alert('dfdsf');
}

JSFIDDLE 演示

这就是

在这些事件中调用的函数的方式 属性必须全局定义(或在那里定义(,而不是在任何包装函数中。更好的解决方案是附加事件处理程序。

$(document).ready(function() {
function artistGen(){
    alert(this.href);
};
$.each(data, function() {
    var $li = $('<li><a href="http://...../100.php" artist="'+ this.name +'" subgenre="'+ this.subgenre +'">' + this.name +     this.new + '</a></li>');
    $li.find('a').on('click', artistGen);
    $('#artist-suggestions').append($li)
});
});