我有一个JavaScript文件在这里http://www.problemio.com/js/problemio.js,我试图将一些jQuery代码为它看起来像这样:如何放置一个jQuery片段成为一个全球性的文件
$(document).ready(function()
{
queue = new Object;
queue.login = false;
var $dialog = $('#loginpopup')
.dialog({
autoOpen: false,
title: 'Login Dialog'
});
var $problemId = $('#theProblemId', '#loginpopup');
$("#newprofile").click(function()
{
$("#login_div").hide();
$("#newprofileform").show();
});
// Called right away after someone clicks on the vote up link
$('.vote_up').click(function()
{
var problem_id = $(this).attr("data-problem_id");
queue.voteUp = $(this).attr('problem_id');
voteUp(problem_id);
//Return false to prevent page navigation
return false;
});
var voteUp = function(problem_id)
{
alert ("In vote up function, problem_id: " + problem_id);
queue.voteUp = problem_id;
var dataString = 'problem_id=' + problem_id + '&vote=+';
if (queue.login = false)
{
// Call the ajax to try to log in...or the dialog box to log in. requireLogin()
}
else
{
// The person is actually logged in so lets have him vote
$.ajax({
type: "POST",
url: "/problems/vote.php",
dataType: "json",
data: dataString,
success: function(data)
{
alert ("vote success, data: " + data);
// Try to update the vote count on the page
//$('p').each(function()
//{
//on each paragraph in the page:
// $(this).find('span').each()
// {
//find each span within the paragraph being iterated over
// }
//}
},
error : function(data)
{
alert ("vote error");
errorMessage = data.responseText;
if (errorMessage == "not_logged_in")
{
//set the current problem id to the one within the dialog
$problemId.val(problem_id);
// Try to create the popup that asks user to log in.
$dialog.dialog('open');
alert ("after dialog was open");
// prevent the default action, e.g., following a link
return false;
}
else
{
alert ("not");
}
} // End of error case
}
}); // Closing AJAX call.
};
$('.vote_down').click(function()
{
alert("down");
problem_id = $(this).attr("data-problem_id");
var dataString = 'problem_id='+ problem_id + '&vote=-';
//Return false to prevent page navigation
return false;
});
$('#loginButton', '#loginpopup').click(function()
{
alert("in login button fnction");
$.ajax({
url:'url to do the login',
success:function() {
//now call cote up
voteUp($problemId.val());
}
});
});
});
</script>
为什么有我两个原因试图做到这一点:
1)我猜这只是一个很好的做法(希望它会更容易跟踪我的全局变量等 2)更重要的是,我试图调用voteUp(someId )函数在problemio.js文件的原始代码中,我收到一个错误,说它是一个未定义的函数,所以我想我会有如果它在全局范围内调用该函数,运气会更好。我的方法正确吗?
所以,我可以将放入此问题的代码复制/粘贴到problemio.js文件中,还是必须删除它的某些部分,如打开/关闭标记? document.ready()函数怎么样?我应该只有全局文件中的一个吗?或者我应该拥有多个并且不会受伤的?
谢谢!
'if(queue.login = false)'不正确,需要两个'=='进行比较。除此之外,使用'{}'而不是'new Object()'并将一个对象而不是一个字符串传递给ajax'data'。最后但并非最不重要的一点,请注意,您可以使用'.data(name [,value])'而不是'.attr('data-name')'。 – ThiefMaster
@ThiefMaster啊好点。修正了我的代码中的==。 – GeekedOut
@ThiefMaster我是一个JS newb,使用{}语法和新的Object()之间有什么区别?我应该如何改变它? – GeekedOut