我有一个代码,可以在单击按钮时动态地从表中的两列(成员、说明)读取值。
从表中读取值的 JQuery:
$(function() {
$('#myButton').on('click', function() {
var myCollection = [];
$('div#body').find('tr:gt(0)').each(function() {
var row = this;
var myObj = {
label: valuefromType($(row).find($(row).find('td:eq(1)').children())),
opis: valuefromType($(row).find($(row).find('td:eq(2)').children()))
};
myCollection[myCollection.length] = myObj;
});
console.log(myCollection)
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
break;
case "span":
return $(control).text();
break;
case "select":
return $(control).val();
break;
}
}
});
});
存储在数组中的按钮点击结果是:
0: Object { label: "1", opis: null }
1: Object { label: "2", opis: "test2" }
2: Object { label: "3", opis: "test3" }
3: Object { label: "5", opis: "3" }
4: Object { label: "9", opis: "test5" }
5: Object { label: "15", opis: "test88" }
现在我需要从位于 table 上方的下拉列表(House Center)中获取所选值(1,2,3,4,5 ...)并在单击按钮时将其存储在数组中。
有人可以帮我吗?
最佳答案
您需要在 click
事件之外声明数组,然后添加绑定(bind)到您的选择的新事件,如下所示:
$('#MainContent_ddlBusinessCenter').on('change', function () {
myCollection.push($(this).val());
});
如果您想以与以前的值相同的方式对其进行排序,请像这样:
$('#MainContent_ddlBusinessCenter').on('change', function () {
var dropdown = $(this);
myCollection.push({label: dropdown.val(), opis: dropdown.find("option:selected").text()});
});
编辑
您可以将此 myCollection[myCollection.length] = myObj;
更改为 myCollection.push(myObj)
。它消耗的内存更少。
并尽量减少使用$()
。
$(function() {
$('#myButton').on('click', function() {
var myCollection = [];
$('div#body').find('tr:gt(0)').each(function(i, e) {
var row = $(e);
myCollection.push({
label: valuefromType(row.find(row.find('td:eq(1)').children())),
opis: valuefromType(row.find(row.find('td:eq(2)').children())),
ddl: $('#MainContent_ddlBusinessCenter').val()
});
});
console.log(myCollection);
});
function valuefromType(control) {
var type = $(control).prop('nodeName').toLowerCase();
switch (type) {
case "input":
return $(control).val();
case "span":
return $(control).text();
case "select":
return $(control).val();
}
}
});
关于javascript - 单击按钮时从表和下拉列表中获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50814464/