Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何检索字段名称_Javascript_Jquery - Fatal编程技术网

Javascript 如何检索字段名称

Javascript 如何检索字段名称,javascript,jquery,Javascript,Jquery,我有一个简单的javascript函数来检查字段是否为空: function notEmpty( field , alert_text ){ if (field.val() === "" || field.val() === null || field.length === 0) { if ( alert_text ){ alert ( 'Error: please enter some text - ' + alert_text ); } /

我有一个简单的javascript函数来检查字段是否为空:

function notEmpty( field , alert_text ){ 
if (field.val() === "" || 
    field.val() === null ||
    field.length === 0) {
    if ( alert_text ){
        alert ( 'Error: please enter some text - ' + alert_text );
    } // end if 
    field.addClass( 'hightlight' );
    field.focus();
    return false;
} // end if
else {
    field.removeClass('hightlight');
    return true;
} // end else
我想在不使用alert_text参数的情况下获取要在警报中显示的字段名称。我尝试了很多方法,但没有成功,所以我将函数保持原样,并使用alert_text参数传递字段名。所有我的表单输入标记都是这样的:

  <input    type=       "text" 
    name=       "artist" 
    id=     'artistfield' 
    size=       "60" 
    tabindex=   "1" />


因此,它们都定义了“名称”。一定有办法把它放进我的警报箱,但我还没弄明白。我相信这很容易,我只是对这很陌生。谢谢。

您可以使用以下内容检索名称:

field_name = field.attr('name');
您可以使用jQuery的方法获取名称(以及几乎任何其他HTML属性):

您可以使用:

field.attr('name')


从字段中获取
name
属性。例如,如果需要字段id,可以更改
id
name

要获取元素的
name
-属性,可以使用-函数。它可以获取任何属性的值


例:

谢谢大家的及时回复-现在一切都好了,干杯
function notEmpty(field) { 
    if (field.val() === "" || field.val() === null || field.length === 0) {
        if (field.attr('name')) {
            alert('Error: please enter some text - ' + field.attr('name'));
        }
        field.addClass('hightlight');
        field.focus();
        return false;
    } else {
        field.removeClass('hightlight');
        return true;
    }
}