【发布时间】:2019-10-11 16:17:16
【问题描述】:
我有一个应用程序,当用户单击“添加新项目”按钮时,使用 Javascript 动态添加行,并且动态添加的行中的每个输入字段都有一个唯一的 id,这很好用。
当点击左侧表格上的任何数字时,它会动态填充到左侧行中。当点击右侧表格上的另一个数字时,它会填充到右侧的单个输入中(加号图标之后)。
当我将鼠标悬停在第一行时,背景颜色变为绿色,包括左侧表格上的相应匹配项,效果很好。
我正在尝试添加一个逻辑 a.) 如果用户点击Add New Item按钮添加新行(该行按照第一行的格式添加)。
b.) 在用户单击 2 个表(左右)上的任何 td 数字后,它们的值会动态填充到行中(左侧表上的值填充在 + 符号之前的行中,右侧的值填充表填充在 + 号之后的右表中),当用户将鼠标悬停在行上的值上时,其背景颜色应立即更改并符合他们先前从中选择的表的值...
NB ~ 基本上我希望在单击按钮后动态添加的后续行中模拟第一行的行为(在鼠标悬停后,当从相应的表中填充输入时)。。 p>
JsFiddle 链接:Js Fiddle
~ 请协助完成这项颇具挑战性的任务..
注释的 JavaScript 代码以显示我在任务中的步骤
//Add row input fields dynamically on button click
// Starting number of inputs
let count = 5;
// Wrapper
const wrapper = document.querySelector("#wrapper");
document.querySelector("#btn").addEventListener("click", () => {
const container = document.createElement("div");
for (let i = 0; i < 5; i++) {
// Increment the count to ensure that it is unique
count++;
// Create new `<input>` element
const input = document.createElement("input");
input.type = "text";
input.name = count;
input.size = "4";
input.id = `inp${count}`;
container.appendChild(input);
// Optional: add empty whitespace after each child
container.append(document.createTextNode(" "));
}
wrapper.appendChild(container);
});
//END creating rows dynamically
let currentInput = 1;
let bonusInput = 1;
//Left table on click event
$("#table1 td").on("click", function(event) {
//gets the number associated with the click
let num = $(this).text();
//Populate it in 1st row input fields (before plus sign)
$("#inp" + currentInput++).attr("value", num);
});
//Right table on click event
$("#table2").on("click", function(event) {
//gets the number associated with the click
let bon = event.target.textContent;
//Populate it in 1st row input fields (after plus sign)
$("#bonus" + bonusInput++).attr("value", bon);
});
//Manipulate background colors of rows with corresponding tables they were
//selected on hover in and hover out
$("input").hover(
function(event) {
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
let num = $(element).val();
//console.log(num);
if (num) {
//Change input color on hover
$(this).css("backgroundColor", "green");
//Change left table bgcolor on hover
$("#table1 td").each(function() {
if ($(this).text() === num) $(this).css("backgroundColor", "green");
});
// $("#table2 td").each(function() {
// if ($(this).text() === num) $(this).css("backgroundColor","green");
// });
}
});
},
function(event) {
//Change input color on hover out
let parent = $(this).parent();
$(parent.children()).each(function(index, element) {
$(element).css("backgroundColor", "white");
});
//Change left table bgcolor on hover out
$("#table1 td").each(function() {
$(this).css("backgroundColor", "orange");
});
}
);
【问题讨论】:
标签: javascript jquery css html-table row