简体   繁体   English

如何使用Javascript将属性中的值获取到另一个属性

[英]How to get a value in an attribute to another attribute with Javascript

<input type="checkbox" onfocus="EnsureSelectionHandlerOnFocus(event,this,12)" onclick="ToggleAllItems(event,this,12)" title="Select or deselect all items" class="s4-selectAllCbx">

Whenever I refresh the page, these attributes have been changed with "12" in both EnsureSelectionHandlerOnFocus and ToggleAllItems. 每当我刷新页面时,这两个属性在EnsureSelectionHandlerOnFocus和ToggleAllItems中都改为“12”。 Therefore, I would like to get "12" of the onfocus and set "12" to the onlick attribute with Javascript? 因此,我想获得onfocus的“12”并使用Javascript将“12”设置为onlick属性?

If I understand you correct, you want to extract the number - the last param of the inline event listeners? 如果我理解你是正确的,你想提取数字 - 内联事件监听器的最后一个参数?

//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);

To set the onclick event number param : 要设置onclick事件编号参数:

var click = 'ToggleAllItems(event, this, NUMBER)';
click = click.replace('NUMBER', number);
document.getElementById('cbSelectAll').setAttribute('onclick', click);

Example alternatives to document.getElementById 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);

or add an unique name to the checkbox : 或者为复选框添加唯一名称:

<input type="checkbox" name="myCheckBox" ...>
var element = document.querySelector('[name="myCheckBox"]');
console.log(element);

both will return the checkbox. 两者都将返回复选框。 If multiple elements has the same class or the same attribute, the first occurrence in the document will be returned. 如果多个元素具有相同的类或相同的属性,则将返回文档中的第一个匹配项。 Giving the checkbox an unique class is prefered, imho, since you will have to update your code each time you change the attribute of the title . 由于每次更改title的属性时都必须更新代码,因此首选复选框是一个唯一的类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM