2009-06-09 59 views
1

以下一段代碼在您點擊鏈接後將焦點輸入文本。它適用於Chrome 2.x,IE8和Opera 9.64,但不適用於Firefox 3.0.9。文本輸入在Firefox中快速閃爍然後消失,我目前正在使用Windows XP SP2。jQuery焦點功能在Firefox中不起作用

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> 
<script> 
$(document).ready(function() 
{ 
    $("a").click(function() { 
     var field_id = $(this).attr("href"); 
     $(field_id).focus(); 
    }); 
}); 
</script> 

<a href="#text_field">Focus</a> 
<input type="text" name="text_field" id="text_field" /> 

有沒有人知道如何在Firefox中處理上述問題?

回答

10

我不知道這是你想要的。爲了把重點放在輸入點擊label你可以這樣做:

<label for="text_field">Label</label> 
<input type="text" name="text_field" id="text_field" /> 

OR

<label>Label 
<input type="text" name="text_field" id="text_field" /> 
</label> 
+0

這是簡單得多,我不需要去通過jQuery的。 – 2009-06-09 20:58:14

+3

:)但jQuery仍然很棒。 – 2009-06-09 21:00:26

1

除了其他兩個答案,你的方式是不工作的原因是因爲價值href字段通常被url完全限定(這取決於瀏覽器,jQuery不會將其抽象出來)。

所以如果你有一個href「#text_field」,你可能會發現該字段的實際值是「http://localhost/#text_field」,這就是它與你的模式不匹配的原因。

如果你想專注於領域,Daniel對標籤和「for」屬性的建議是一個很好的解決方案。

+0

+1 .href包括http:// stuff - 這個'功能'之前也引起了我的注意,也在.src上觀察它。 – gnarf 2009-06-09 20:54:35

0

我認爲FF中出現此錯誤的原因是您點擊鏈接後會運行點擊回調,然後打開頁面#文本框。您可以嘗試:

$(document).ready(function() 
{ 
    $("div").click(function() { 
     var field_id = $(this).attr("forInput"); 
     $(field_id).focus(); 
    }); 
}); 
</script> 

<div forInput="#text_field">Focus</div> 
<input type="text" name="text_field" id="text_field" /> 

這種方式沒有鏈接,不會打開另一個頁面。

1

這應該做的伎倆:

$(function() 
{ 
    $("a").click(function() 
    { 
     $($(this).attr("href")).focus(); 

     return false; // remember to stop links default action 
    }); 
}); 

在Chrome,IE和Firefox的最新版本進行測試。

2

正如Daniel所暗示的,問題在於鏈接上的#text_field。設置焦點後,Firefox想要跳轉到文檔中的指定位置。您所需要做的就是從您的點擊處理程序返回false。

$(field_id).focus(); 
return false; 
0

您也可以更加明確地在事件arg上調用preventDefault

$(document).ready(function() 
{ 
    $("a").click(function(event) { 
     var field_id = $(this).attr("href"); 
     $(field_id).focus() 
     event.preventDefault(); 
    }); 

}); 
1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script> 
<script> 
$(function() { 
    $("a").click(function() { 
     var field_id = $(this).attr("href"); 
     $("#"+ field_id).focus(); 
     return false; 
    }); 
}); 
</script> 

<a href="text_field">Focus</a> 
<input type="text" name="text_field" id="text_field" />