2010-11-03 77 views
0

我有一個關於jQuery Validator插件中的errorPlacement方法的問題: 我想把一個錯誤消息放在div中。問題與jQuery驗證器中的errorPlacement

之前我繼續...是的,代碼是可怕的,我正在一個不是我的項目,沒有文檔或任何我幫助我。但我不能從零寫所有的網頁。

好吧,讓我們繼續,這是HTML代碼的一個小部分:

<tr> 
    <th height="24" scope="col"> 
    <div align="left" class="Style69 Style72 Style75"> 
     <span class="Style77">Name</span> 
    </div> 
    </th> 
    <th height="24" colspan="3" scope="col"> 
    <div align="left"> 
     <span class="Style69 Style72 Style75"> 
     <input id="txtname" name="txtname" class="required" 
     type="text" size="30" /> 
     </span> 
    </div> 
    </th> 
</tr> 
<tr> 
    <td height="17" colspan="4"> 
    <div id="errorMessage"></div> 
    </td> 
</tr> 

佈局是一個表,這表內放置的所有元素(inputboxes和選擇的)。

我的問題是,我怎麼能把錯誤消息放在div「errorMessage」?

我在做這樣的事情:

errorPlacement: function(error, element) { 
    error.appendTo(element.prev().next().next()); 
} 

但它不工作。然後,我試過這個:

errorPlacement: function(error, element) { 
    error.appendTo(element.prev().next().next().find("#errorMessage")); 
} 

沒有任何反應。 「Div」和「Span」標籤是DOM的一部分嗎?

有何建議?

+2

您的網頁是否包含「的errorMessage」除不止一次?如果你的答案是否定的,可能只是$(「#errorMessage」)。html(error);足夠。 – anilca 2010-11-03 13:48:10

+1

是的,anilca說什麼!元素ID必須是唯一的,因此您的頁面上只能有一個ID爲「errorMessage」的元素。所以,你需要做的是選擇這個元素是$('#errorMessage')'。 – 2010-11-03 14:04:03

+0

@Matt Ball非常感謝!給你和anilca。真的有效!是的,我知道,網頁中的所有Div ID都是唯一的。 – 2010-11-03 14:10:05

回答

2

在這裏的問題是,.prev()沒有給出結果,沒有一個同級到您的<input>這裏:

<span class="Style69 Style72 Style75"> 
    <input id="txtname" name="txtname" class="required" 
    type="text" size="30" /> 
    </span> 

像這樣的東西應該工作:

errorPlacement: function(error, element) { 
    element.closest('tr').next().find('.errorMessage').append(error); 
} 

這使用.closest()要上去<tr>,得到.next()兄弟姐妹(下一個<tr>),然後.find()得到內部的class="errorMessage"元素。

有了這個,改變你的id一類,像這樣:

<div class="errorMessage"></div> 
+0

是的,它也行得通!非常感謝!您的解決方案和anilca的解決方案非常完美。而且,我對這個問題抱歉,我真的是一個Begginer。感謝你們! – 2010-11-03 14:14:31

+0

@Astantler - 這是一個完美*有效的問題,歡迎:) – 2010-11-03 14:15:29