簡體   English   中英

在jQuery中設置元素的HTML屬性

[英]Setting the HTML property of an element in jQuery

請檢查代碼..

$(".editable").live("click",function(){
CurrentOBJhtml = $(this).text();
nextHtml = "<input type='text' class='hoverable' value='"+CurrentOBJhtml+"'  />";
var c = nextHtml;
alert(c); //here two alert box comes....
$(this).html(c);

});

當我警告c時,它會在兩個警告框中提醒兩個值......

第一個值是<input type='text' value='myname' class='hoverable' />第二個是<input type='text' value='' class='hoverable' />其中第二個沒有value

當我評論最后一行( $(this).html(c); )然后它只給出第一個結果。

我有什么問題? 我完全糊塗了。

請幫我解決這個問題。

謝謝 。

更新:

HTML:

  <fieldset id="user_info_module">
<label>username:</label>
<label class="editable" id="user_info_username">
<label>Email:</label>
<label id="user_info_email"> </label>
<label>Default page:</label>
<label id="user_info_defaultpage"></label>
<label>mobile:</label><label id="user_info_mobile"></label>
<label>country:</label><label id="user_info_country"></label>
<label>address:</label><label id="user_info_address"></label>
<label>pincode:</label><label id="user_info_pincode"></label>
<label>landline:</label><label id="user_info_landline"></label>
</fieldset>

http://jsfiddle.net/M3J2p/1/

可能是您有兩個“可編輯”類的元素,或者您調用上面兩次的代碼。 你在document.ready中有嗎? 或通過功能調用它?

首先把你的jquery代碼放在$(document).ready(function())中; 處理程序。

並檢查這個jsfiddle ,它沒有向我顯示任何雙重警報框。 當您單擊一個元素時, this將引用該特定元素而不是其他元素。

更新您的html代碼以確認確切的問題或為您的問題創建一個示例jsfiddle。

編輯:錯誤原因並解決了

在jQuery 1.7之前,為了阻止進一步的處理程序在使用.live()進行綁定之后執行,處理程序必須返回false。 調用.stopPropagation()不會實現此目的。

$("a").live("click", function(event){
  event.preventDefault();
});

根據您的代碼檢查更新的jsfiddle 你錯過了關閉一個標簽,並且當你使用它時發生上述事件冒泡問題。 在更新的jquery中使用.on() ..

檢查jQuery上的.live()文檔,以便更好地了解這一點。

我想$(“。editable”)找到多個元素。 如果要查找特定元素,請考慮使用Id,或者還可以檢查目標是否是回調中的正確目標。

$(".editable").live("click",function(event)
{
   if (event.target == mytarget)
   {
         // do something
   }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM