我有以下代码,我想从模式的页脚中的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>
答案 0 :(得分:0)
此 _id var声明应该适合您:
// declare an upper variable
// to make it available for child scopes
var _id = null;
$.ajax({
...
success: function(data) {
var obj = jQuery.parseJSON(data);
$(".contributions").click(function() {
_id = this.id // save this var for later use!
document.getElementById("editinputtext").value = obj[_id];
});
}
});
$("#EDITsave").click(function() {
var a = _id // access the above id var here!!!
...
});
&#13;
答案 1 :(得分:0)
您需要在最外层范围内声明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