javascript - JQuery - 将 JS 转换为 JQuery 以生成允许解析 URL 参数的表

标签 javascript jquery html url

我在将普通 JS 代码转换为 JQuery 时遇到问题。我需要从 URL 获取参数值。 例如:

localhost:63342/2018-11-13-html/form_sent.html?phone=4325325235&adress=testadress&order=book1&order=book2&deliverydate=datadostawy&deliverymethod=chinamail&agree=on

我当前的尝试是生成 [Object object] 来代替它应该丢弃的值。

function createSimpleRow(header, value) {
    const urlParams = new URLSearchParams(window.location.search);
    return $("<tr></tr>").append($("<th></th>").text(header)).append($("<td></td>").text(`${urlParams.getAll(value)}`));
}

function readBookOrder(booklist) {
    const list = document.getElementById(booklist);
    const table = document.createElement("table");


    table.append(createSimpleRow("phone", `phone`));
    table.append(createSimpleRow("adress", `adress`));

    list.appendChild(table);
    return list;
}

我的旧代码是 Jquery 和纯 JS 的混合体,它似乎工作正常,给出了我指定从 URL 获取的所有值。

function readBookOrder(booklist) {
    const list = document.getElementById(booklist);
    const table = document.createElement("table");

     const tr = document.createElement("tr");
     const td1 = document.createElement("td");
     td1.innerHTML = `${urlParams.get("phone")}`;
     tr.appendChild(td1);
     const td2 = document.createElement("td");
     td2.innerHTML = `${urlParams.get("adress")}`;
     tr.appendChild(td2);
     const td3 = document.createElement("td");
     td3.innerHTML = `${urlParams.getAll("order")}`;
     tr.appendChild(td3);
     const td4 = document.createElement("td");
     td4.innerHTML = `${urlParams.get("deliverydate")}`;
     tr.appendChild(td4);
     const td5 = document.createElement("td");
     td5.innerHTML = `${urlParams.get("deliverymethod")}`;
     tr.appendChild(td5);

    table.appendChild(tr);
    list.appendChild(table);
    return list;
}

有人可以建议我在转换为 JQuery 标准期间错过了什么吗?

最佳答案

由于 createSimpleRow() 现在返回一个 jQuery 对象,因此您无法使用 native DOM 方法直接附加该对象。

readBookOrder() 转换为使用 jQuery 方法,而不是允许插入其他 jQuery 对象

function readBookOrder(booklist) {
    const $list = $(`#${booklist}`);
    const $table = $("<table>");

    ['phone', 'adress'].forEach(e => $table.append(createSimpleRow(e, e)) );       

    $list.append($table);
    return $list;
}

在变量名中添加 $ 前缀是一种常见的做法,以反射(reflect)该变量包含 jQuery 对象

关于javascript - JQuery - 将 JS 转换为 JQuery 以生成允许解析 URL 参数的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54618123/

相关文章:

javascript - 如何用js提取网页中当前所有的视频文件及其地址?

javascript - 在 Vue 项目中使用 jQuery 是否更可取?

javascript - 转换json选择数据

javascript - 如何将生成的php页面中的数据显示到另一个页面?

javascript - console.log 不解析 css 样式

javascript - UIkit 3 的 Filter 组件 : Set active filter with URL hash - unable to change active filter with JS

javascript - 悬停缓动 jQuery

javascript - 同位素 : jQuery not a function error using either jQuery or $ in WordPress

javascript - 如何使用 IntersectionObserver 使我的框只出现一次?

html - Angular 9 Keyvalues 管道不是为生产而构建的