我有以下代码,我想从模态脚注中的ajax函数访问id,无论如何我都能做到,我尝试创建自己的命名空间或在函数外部设置变量
document.getElementById('editinputtext').style.height="200px";
document.getElementById('editinputtext').style.width="850px";
$.ajax({
type: "GET",
url : '/Proto/PHP/connect.php',
datatype : 'json',
success : function(data){
var obj = jQuery.parseJSON(data);
$(".contributions").click(function(){
var id = this.id // I need to save this var for later use!
document.getElementById("editinputtext").value =obj[id];
});
}
});
</script>
</div>
<div class="modal-footer">
<button id="EDITcancel" type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button id="EDITsave" type="button" class="btn btn-default" data-dismiss="modal">Save</button>
<script>
$( "#EDITsave" ).click(function() {
var a = id //I want to access the above id var here!!!
$.ajax({
type: "POST",
datatype: "text",
url: "/Proto/PHP/edit.php",
data: {contribution_id: a+1, content: document.getElementById("editinputtext").value, storyID:1},
});
window.location.reload(false);
});
</script>
最佳答案
您需要在最外部的作用域中声明var id
,以便在以后的单击处理程序函数中可以访问它:
var id;
$.ajax({
type: "GET",
url : '/Proto/PHP/connect.php',
datatype : 'json',
success : function(data){
var obj = jQuery.parseJSON(data);
$(".contributions").click(function(){
id = this.id //same var id as declared above
//etc...
<script>
$( "#EDITsave" ).click(function() {
var a = id //same var id as declared above