![](/img/trans.png)
[英]How can I get the user id in js file dynamically if the js file is embedded in another site
[英]How to get field id dynamically in js file?
鑒於我的聯系表為:
<?php echo $this->Form->create(); ?>
<ul>
<li>
<?php echo $this->Form>input('Name',array('id'=>'name','class'=>'default'));?>
</li>
<li>
<?php echo $this->Form->input('Address',array('id'=>'address','class'=>'default'));?>
</li>
<li>
<?php echo $this->Form->input('Email',array('id'=>'email','class'=>'default'));?>
</li>
<li>
<?php echo $this->Form->input('Phone',array('id'=>'phone','class'=>'default'));?>
</li>
<li>
<?php echo $this->Form->textarea('Enquiry',array('id'=>'enquiry','class'=>'default'));?>
</li>
</ul>
<?php echo $this->Form->end(__('Submit')); ?>
在js文件中,我有:
$(document).ready(function(){
$('.default').blur(function(){
$.post(
'/cakephp/Packages/validate_form',
{field:$(this).attr('id'),value:$(this).val()
},
handleNameValidation
);
});
function handleNameValidation(error){
if(error.length>0){
if($('#name-notEmpty').length==0){
$('#name').after('<div id="name-notEmpty" class="error-message">'+ error + "</div>");
}
}
else{
$('.error-message').remove();
}
}
});
在這里,我動態地收到錯誤消息,但是無法在以下位置動態獲取字段ID:
$('#name').after('<div id="name-notEmpty" class="error-message">'+ error + "</div>");
在這里,我將字段ID定義為#name
靜態,但希望該字段動態進行。任何幫助,
由於我已經解決了這個問題,因為:
$(document).ready(function(){
$('.default').blur(function(){
var self = this;
$.post(
'/cakephp/Packages/validate_form',
{field:$(this).attr('id'),value:$(this).val()
},
function(error){
handleNameValidation(error,self)
}
);
function handleNameValidation(error,el){
var $parent = $(el).parent();
if(error.length>0){
if($('span.error-message',$parent).length==0){
$parent.append('<span class="error-message">'+ error + '</span>');
}
else{
$('span.error-message',$parent).replaceWith('<span class="error-message">'+ error + '</span>');
}
}
else{
$parent.removeClass('error-message');
$('span.error-message',$parent).fadeOut();
}
}
});
我剛剛修改了您的代碼,但未對其進行測試。 嘗試一次
$(document).ready(function(){
$('.default').blur(function(){
var fieldID=$(this).attr('id');
$.post(
'/cakephp/Packages/validate_form',
{field:fieldID,value:$(this).val()
},
handleNameValidation(error,fieldID);
);
});
function handleNameValidation(error,fieldID){
if(error.length>0){
if($('#name-notEmpty').length==0){
$('#'+fieldID).after('<div id="name-notEmpty" class="error-message">'+ error + " </div>");
}
}
else{
$('.error-message').remove();
}
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.