我想帮助简化脚本中的代码。我的代码中有很多重复的部分需要处理,而且不容易跟上。这是代码:
// ==UserScript==
// @run-at document-idle
// @name my script
// @version 0.1
// @author me
// @match http://website.com/
// @grant GM_addStyle
// @grant GM_xmlhttpRequest
// @require http://code.jquery.com/jquery-latest.js
// @require https://raw.githubusercontent.com/sunnywalker/jQuery.FilterTable/master/jquery.filtertable.js
// ==/UserScript==
/* jshint -W097 */
setInterval(bprs, 600000);
setTimeout(bprs, 4000);
function bprs() {
{
var accountname1 = $('#accountName1').text(); // points to the first account field - please add more depending on how many accounts you have 'accountName2,accountName3,4,5...'
var credits1 = $('#credits1').text(); // points to the first credits field - please add more depending on how many accounts you have 'credits2,credits3,4,5...'
var accountname2 = $('#accountName2').text();
var credits2 = $('#credits2').text();
var accountname3 = $('#accountName3').text();
var credits3 = $('#credits3').text();
var accountname4 = $('#accountName4').text();
var credits4 = $('#credits4').text();
var accountname5 = $('#accountName5').text();
var credits5 = $('#credits5').text();
var accountname6 = $('#accountName6').text();
var credits6 = $('#credits6').text();
var date = new Date();
var data = "date=" + date +
// "&accountname1=" + accountname1 + "&credits1=" + credits1 new entires must be added depending on how many accounts you have
"&accountname1=" + accountname1 + "&credits1=" + credits1 +
"&accountname2=" + accountname2 + "&credits2=" + credits2 +
"&accountname3=" + accountname3 + "&credits3=" + credits3 +
"&accountname4=" + accountname4 + "&credits4=" + credits4 +
"&accountname5=" + accountname5 + "&credits5=" + credits5 +
"&accountname6=" + accountname6 + "&credits6=" + credits6;
//Changes must also be added to the PHP script
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
options.async = true;
});
$.ajax({
url: 'http://mywebsite.com/submit.php', // point to the php file here
async:false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
}
}

理想情况下,我希望将积分和帐户名称条目缩短为循环,用户可以配置在页面上查找的帐户数量,而无需设置积分条目。
答案 0 :(得分:1)
当你有这种重复模式,尤其是自然索引(account1,2,3 ......)时,你应该真正使用数组。
以下是如何简化重复部分并使用变量配置数量的方法:
function bprs() {
// Change this variable depending on how many accounts you have
var accountsCount = 6;
var accounts = [];
for (var n = 1; n <= accountsCount; n++) {
// Using objects literals to group your data is a great way to make your code clearer
accounts[n] = {
name: $('#accountName' + n).text(),
credits: $('#credits' + n).text()
};
}
var date = new Date();
var data = "date=" + date +
accounts.reduce(function (prev, account, n) {
return prev + "&accountname" + n + "=" + account.name +
"&credits" + n + "=" + account.credits;
}, '');
//...
我假设你也可以自动设置accountsCount
变量,例如,如果帐户元素附加了特定的类:
var accountsCount = document.getElementsByClassName('SPECIFIC_CLASS').length;