2014-12-20 73 views
1

我有一些麻煩,試圖存儲一些動態鏈接,我用ajax後響應創建的url參數。 ajax的帖子工作正常,名字和subgenre vars正在從ajax響應中正確填充。現在我想要發生的是,用戶點擊其中一個生成的網址,網址內的參數,即subgenre =「blah」,將被髮送到數據庫並存儲。我遇到的問題是標準事件點擊功能在文檔就緒功能內部或外部不起作用。抓取url參數onclick的url .. jquery,Javascript

$(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功能,以下,但由於它是文檔範圍之外,我不能用「這個」查詢。我必須將onclick函數放在文檔就緒函數之外,否則它將無法工作。

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

}; 

我在這裏錯過了什麼或者我做錯了什麼?

回答

1

當您製作每個元素時,您可以在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'); 

}; 
+0

現在嘗試這一權利,但它沒有經過論證。我想知道是否有範圍 – Brandon

+0

得到它呢!隨着一些主要的MODS,我得到它的工作! – Brandon

+1

糟糕,我認爲有一些拼寫錯誤,但很高興你能夠正常工作。 – Seano666

0

這只是它是如何被稱爲在那些事件屬性功能是全局定義(或定義在那裏)沒有任何包裝的功能。更好的解決方案是附加事件處理程序。

$(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) 

}); 

}); 
+0

當我嘗試類似的東西時碰到的問題是,藝術家變量在每次循環創建下一個鏈接時被覆蓋。如果我能找到一個簡單的解決方案被覆蓋,那麼問題就解決了! – Brandon

+0

但您不使用藝術家變量。 – Musa

+0

那麼設置全局變量的意義何在?我很困惑 – Brandon

0

在jQuery的動態元素,你可以通過這種方式

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

,或者你可以用你的方式繼續使用功能,但只是添加參數到功能使用click事件 像

function artistGen(Artist){ 
    // do something 
}; 
0

您需要從的​​

012範圍中刪除 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 DEMO

+0

我沒有從加載函數中刪除函數,這是我的問題來自何處。使用$ this來獲取參數會很好,但是使用load函數之外的函數會改變這個範圍,我不能把它帶到函數 – Brandon

+0

你可以把參數傳遞給函數調用嗎? 'artistGen(參數)' – JRulle