<input type="checkbox" onfocus="EnsureSelectionHandlerOnFocus(event,this,12)" onclick="ToggleAllItems(event,this,12)" title="Select or deselect all items" class="s4-selectAllCbx">
每当我刷新页面时,EnsureSelectionHandlerOnFocus 和 ToggleAllItems 中的这些属性都会更改为“12”。因此,我想获取onfocus的“12”并用Javascript将“12”设置为onlick属性?
最佳答案
如果我理解正确,您想提取数字 - 内联事件监听器的最后一个参数?
//get the event, example EnsureSelectionHandlerOnFocus(event,this,12)
var event = document.getElementById('cbSelectAll').getAttribute('onfocus');
//extract the params, example event,this,12
var params = event.match(/\(([^)]+)\)/)[1];
//get the last param, example 12
var number = params.split(',')[2];
//outputs 12
console.log(number);
设置 onclick 事件编号参数:
var click = 'ToggleAllItems(event, this, NUMBER)';
click = click.replace('NUMBER', number);
document.getElementById('cbSelectAll').setAttribute('onclick', click);
<小时/>
document.getElementById 的替代示例
//selecting the checkbox by its class (if the class is unique)
var element = document.querySelector('.s4-selectAllCbx');
console.log(element);
//alternatively selecting the checkbox by an attribute
var element = document.querySelector('[title="Select or deselect all items"]');
console.log(element);
或向复选框添加唯一名称:
<input type="checkbox" name="myCheckBox" ...>
var element = document.querySelector('[name="myCheckBox"]');
console.log(element);
两者都会返回复选框。如果多个元素具有相同的类或相同的属性,则返回文档中第一个出现的元素。恕我直言,最好为复选框提供一个唯一的类,因为每次更改 title
的属性时都必须更新代码。
关于javascript - 如何使用 Javascript 将属性中的值获取到另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22833206/