0

我在网格中有一个下拉菜单。这就是它的样子。现在我正在尝试获取选择标签的名称。
var x = document.getElementsByTagName('select'); 我需要获取名称并以这种方式对其进行解析以获取此值13442111。获取此信息的最佳方式是什么?

<td class="cl">
    <select name="ctrlvcol%3DId%3Bctrl%3DTabListView%3Brow%3D13442111%3Btype%3Dtxt" onchange="getTypeValue(this.value,13442111)">
       <option value="1025">TEST-AAAA</option>
       <option selected="" value="1026">TEST-BBBB</option>
       <option value="1027">TEST-CCCC</option>
    </select>
</td>
4

2 回答 2

1
var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;

for (var i = 0; i < selectElementsLen; i++) {

    // split row parts
    var rowID = unescape(selectElements[i].name).split(';');
    if (rowID.length >= 3) {

        // trim meta
        rowID = rowID[2].replace(/^row=/, '');

        // validate row ID
        if (/^[0-9]+$/.test(rowID)) {
            console.log('Valid Row ID: ' + rowID);
            // do whatever needs to be done
        }
    }
}

http://jsfiddle.net/N4sJv/

Here's the approach with regular expression only:

var selectElements = document.getElementsByTagName('select');
var selectElementsLen = selectElements.length;

for (var i = 0; i < selectElementsLen; i++) {

    // extract Row ID
    var rowID = unescape(selectElements[i].name).match(/(?:row=)([0-9]+)/);
    if (rowID && (rowID.length >= 2)) {
        rowID = rowID[1];
        console.log('Valid Row ID: ' + rowID);
        // do whatever needs to be done
    }
}

http://jsfiddle.net/N4sJv/1/

Keep in mind that document.getElementsByTagName() may not be the best choice as it selects all specified elements in the DOM tree. You might want to use a framework such as jQuery to consider browser compatibilities and performance.

于 2013-08-05T20:14:59.273 回答
0

这是一些可能对您有所帮助的代码。当且仅当这是select页面上唯一的元素时,这个小片段才会起作用。正如上面的评论所说,最好用id. 但是,对于您的用例,以下内容应该有效:

// Get all select elements (in this case the one) on the page.
var elems = document.getElementsByTagName("select");

// Select the first "select" element and retrieve the "name" attribute from it
var nameAttr = decodeURIComponent(elems[0].getAttribute("name"));

// Split the decoded name attribute on the ";" and pull the second index (3rd part)
var nameProp = nameAttr .split(';')[2];

// Substr the name prop from the equal sign to the the end
nameProp = nameProp.substr(nameProp .indexOf('=') + 1);
于 2013-08-05T20:16:15.793 回答