2016-08-21 147 views
0

目前我有一个功能,完美的IE浏览器,Chrome浏览器和Safari浏览器,以获得我将重点放在一个GridView的文本框的ID名称。替代event.srcElement.id

function onTextFocus() { 
     alert(event.srcElement.id); 
    } 

功能是为GridView一个的RowDataBound时呼吁:

protected void ItemGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     ((TextBox)e.Row.FindControl("txtQuantity")).Attributes.Add("onfocus", "onTextFocus();");    
    } 
} 

但是它并不适用于Firefox的工作,因为它不承认srcElement。所以我正在寻找一种适用于所有浏览器的替代方案。淘宝谷歌后,我想出了这些替代品,但我得到一个未定义的错误或ReferenceError。任何想法为什么?

function onTextFocus() { 
     alert(this.id); 
     alert(event.currentTarget.id); 
     alert(event.target.id);  
     alert(event.currentTarget); 
     alert(event.target);       
     alert($(this).attr('id')); 
     alert($(obj).attr("id"));    
     alert($(this).id); 
     alert($(this).get(0).id);    
     alert($(this).prop("id")); 
    } 
+0

显示您在哪里如何使用方法 – Satpal

+0

是问题解决了,可还是需要一些帮助? –

回答

0

开始更新现在,我看到的dotNet代码:

protected void ItemGridView_RowDataBound(object sender, GridViewRowEventArgs e) 
{ 
    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
     ((TextBox)e.Row.FindControl("txtQuantity")).Attributes.Add("onfocus", "onTextFocus(event);");    
    } 
} 

如果添加event参数应该通过它

而是取决于在什么你真的想在那里做更好的方法。

末更新

简短的回答是使用event.target这里是MDN https://developer.mozilla.org/en-US/docs/Web/API/Event/target规范就说明它是由主流浏览器的支持。在你的情况下,你必须在你的事件处理函数中添加参数event

function onTextFocus(event) { 
    alert(event.target.id); 
} 

如果您不声明event参数,则无法访问它。 (这也取决于你如何结合事件)

随着标准的JavaScript(退房https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener),短的例子在这里:

window.onload = function(){ 
 
    
 
    document.getElementById("test").addEventListener('focus', onclick1); 
 

 
    function onclick1(event){ 
 
     console.info(event.target.id); 
 
    } 
 
};
<input type="text" id="test" />

使用jQuery(退房此链接http://api.jquery.com/on/)简短示例:

$(function(){ 
 
    
 
    $("#test1").on('focus', onclick1); 
 

 
    function onclick1(event){ 
 
     console.info(event.target.id); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="text" id="test1" />