将cliendid从控件传递为ASP中的参数到javascript函数

时间:2017-08-01 23:34:31

标签: javascript c# jquery asp.net

我有一个功能,可以在文本框中显示密码,另一个隐藏它并显示点。

这是其中之一:

function MouseOver_MudarTipoPassword() {
        document.getElementById('<%= tb_PalavraPasse.ClientID %>').setAttribute('type', 'singleline');
    }

具有事件的控件:

<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword()" onmouseout="MouseLeave_MudarTipoPassword()" />

所以,我一直在清理代码,因为在多个页面上都使用了函数,我将它们组合成一个javascript文件。如果我把它放在页面的head部分,它就像这样工作。但我想通过一个论点来代替。我想传递文本框clientid。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

使该函数采用参数:

function MouseOver_MudarTipoPassword(elementId) {
        document.getElementById(elementId).setAttribute('type', 'singleline');
    }

将id传递给函数调用:

<img id="img_Eye" runat="server" src="~/Recursos/Imagens/eye-icon.png" onmouseover="MouseOver_MudarTipoPassword('img_Eye')" onmouseout="MouseLeave_MudarTipoPassword('img_Eye')" />
  

更新

道歉,我对这个问题没有给予足够的重视。我的答案的问题是脚本必须在创建DOM之前运行,就像在HEAD中一样。

要使其按预期工作,您必须将事件侦听器附加到元素。您还需要一种动态关联侦听器代码目标的方法。您可以使用data-*属性执行此操作。

See this fiddle for working example

示例标记:

<input type="text" id="theTextBox" value="The IT Crowd" />
<hr />
<img id="Moss" src="https://media0.giphy.com/media/TrDxCdtmdluP6/giphy.gif" data-target="theTextBox" />

在 示例javascript:

var test = document.getElementById("Moss");

test.addEventListener("mouseover", MouseOver_MudarTipoPassword, false);

function MouseOver_MudarTipoPassword( event ) {   
    var theImg = event.srcElement;
    var target = theImg.dataset.target; //re-use this function by applying data-target to all elements that need it (does not have to be named "target")
    document.getElementById(target).setAttribute('type', 'password');
  }
相关问题