Я сделал некоторый код для проверки URL, если у него есть строка запроса, а затем, если он использовал JavaScript, добавлял элементы в поля ввода. Теперь способ, которым я это сделал, работает.Тем не менее, потому что это более просто, я продолжаю добавлять новые тесты в будущее, которые просто раздувают мой код.Я попытался преобразовать в более объектно-ориентированный метод, чтобы моя функция была такой же, но я могу просто добавить новую переменную в массив, чтобы мне не приходилось дублировать функцию, но она не работает, и я не совсем уверен, как получится (Я все еще новичок в объектно-ориентированном)
Я попытался преобразовать его в объектно-ориентированный как так (часть кода, с которым я получил помощь) Это моя попытка, которая не сработала *обратите внимание, что код, о котором я говорю, находится в function init()
* Обратите внимание, что функция init()
вызывается выше, чтобы запускать ее автоматически при загрузке страницы, чтобы проверить, есть ли строка запроса или нет
function getUrlVars(urlVariable) {
var vars = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
if (key === urlVariable) vars[key] = value;
}
);
return vars;
}
function init() {
var screensize = screen.width;
var itemQuery = {
moreBikes:{
urlVar: getUrlVars("currentbike"),
selector: '#currentbikes',
newElement: '<div class=""><input type="text" name="currentbike[]" class="currentbikesadd" value="${morebikes[i]}" ><button class="delete">Delete</button></div>',
oldElement: '<input type="text" name="currentbike[]" class="currentbike">'
}
}
if (urlVar) {
var item = itemQuery[item];
let urlVaribale = item.urlVar.split('_');
for (let i = 0; i < item.urlVaribale.length; i++){
$(item.selector).append(decodeURI(item.newElement))
}
} else if (!urlVar) {
$(item.selector).append(item.oldElement);
}
}
Я пытался сделать что-то подобное, но это не сработало.(Я думаю, что это может быть связано с отсутствием жизнеспособного в init()
, но не слишком уверен. Также в будущем, когда я добавлю другие мои поля, поскольку некоторые из них имеют другие проверки на месте (см. Код ниже для моего старого кодаи что я имею в виду, есть некоторые другие поля) . Итак, как бы я мог объединить его в одно? Ниже приведена более старая (рабочая) не объектно-ориентированная версия кода
thisоригинальная версия моего кода, которая работает
function getUrlVars(urlVariable) {
var vars = {};
window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
if (key === urlVariable) vars[key] = value;
}
);
return vars;
}
function init() {
var screensize = screen.width;
var othersocial_p = getUrlVars("kothersocial");
var othersocialqty_p = getUrlVars("kothersocialqty");
var morebikes_p = getUrlVars("currentbike");
//more bikes
if (morebikes_p['currentbike']) {
//create the array
let morebikes = morebikes_p['currentbike'].split('_');
//loops
for (let i = 0; i < morebikes.length; i++) {
$(wrapper_bike).append(decodeURI(`<div class=""><input type="text" name="currentbike[]" class="currentbikesadd" value="${morebikes[i]}" ><button class="delete">Delete</button></div>`))
}
} else if (!morebikes_p['currentbike']) {
$(wrapper_bike).append(`<input type="text" name="currentbike[]" class="currentbike">`);
}
//other social media
if (othersocial_p['kothersocial'] && othersocialqty_p['kothersocialqty']) {
//create the array
let othersocial = othersocial_p['kothersocial'].split('_');
let othersocialqty = othersocialqty_p['kothersocialqty'].split('_');
if (screensize < 800) {
//loops the length of the username
for (let i = 0; i < othersocial.length; i++) {
$(wrapper_othersocial).append(decodeURI(`<div class="more800 A"><label for="othersocial" id="othersocialmedia">Other - Please specify <br><input name="othersocial[]" class="othersocial addedothersocial" value="${othersocial[i]}" style="margin-bottom:5px;"></label><label for="otherqtys" id="otherqty"> Followers Count: <br>
<input name="otherqty[]" class="otherqtys addothersocquantity" value="${othersocialqty[i]} " style="margin-bottom:5px;" ></label><button style="margin-top:10px;" class="delete">Delete</button><div class="clearfix"></div></div>`));
}
} else {
$(othersocialid).append(`<div class="more800 b"><label for="othersocial" id="othersocialmedia">Other - Please specify <br></label><label for="otherqtys" id="otherqty"> Followers Count: <br></label> <div class="clearfix"></div></div>`);
//loops the length of the username
for (let i = 0; i < othersocial.length; i++) {
$(wrapper_othersocial).append(decodeURI(`<input name="othersocial[]" class="othersocial addedothersocial" value="${othersocial[i]}" style="margin-bottom:5px;"><input name="otherqty[]" class="otherqtys addothersocquantity" value="${othersocialqty[i]} " style="margin-bottom:5px;" ><button style="margin-top:10px;" class="delete">Delete</button></div>`));
}
}
} else if (!othersocial_p['kothersocial']) {
counter_social++;
if (screensize < 800) {
$(othersocialid).append(`<div style="display:inline-block;width: 100%;;" class="less800">
<label for="othersocial" id="othersocialmedia">Other - Please specify <br><input type="text" name="othersocial[]" id="othersocial" class="othersocial"></label>
<label for="otherqtys" id="otherqty"> Followers Count: <br><input type="text" name="otherqty[]" id="otherqtys" style="margin: 10px 0"></label> <div class="clearfix"></div></div>`)
} else {
$(othersocialid).append(`<div class="more800"><label for="othersocial" id="othersocialmedia">Other - Please specify <br><input type="text" name="othersocial[]" id="othersocial" class="othersocial"></label><label for="otherqtys" id="otherqty"> Followers Count: <br><input type="text" name="otherqty[]" id="otherqtys" style="margin: 10px 0"></label> <div class="clearfix"></div></div>`)
}
}
}
В основном код выполняет проверку на наличие в строке запроса массива, относящегося к переменной, оканчивающейся на variable_p[''].split('_')
и разделяет их, так как я сохранил их в виде массива в строке запроса.
Тогда это место, где он разбивается на элементы, у которых есть 1 элемент:
как и больше велосипедов, он идет прямо в for loops
выведите значение, куда он пойдет, чтобы проверить, нет ли значения в строке запроса, а затем просто введите пустое поле ввода
Однако для разбиений, которые имеют 2 элемента:
first checkдля размера экрана, в зависимости от размера экрана, он будет немного отличаться.Таким образом, в зависимости от размера экрана будут отображаться разные макеты одной и той же информации в разном порядке.Еще как прежде, он покажет пустые входные данные, но также в зависимости от размера экрана имеет немного различную компоновку.
Есть ли способ сделать это в одну объектно-ориентированную функцию, или я должен разделить функцию на функции с 2 переменными иразделение экрана по размеру или есть способ проверить это и просто сделать это как одну простую функцию?Любая помощь будет оценена