Refactor if JavaScript

0

I would like to know what is the best way to refactor this code so that it is less repeated.

if($('#edit-tipo-documento').exists()){
    $('head').append('<meta name="TagAutomataAccion1" content="home">')
}

if($('.linea_restablecer').exists()){
    $('head').append('<meta name="TagAutomataAccion1" content="restablecer contraseña">')
}

if($('#edit-contrasena1').exists()){
    $('meta[name=TagAutomataAccion1]').attr("content", 'homeCampaña');
}
    
asked by Oscar Diaz 10.08.2017 в 23:23
source

1 answer

-1

I see it quite simple, if you are going to repeat it more times you could generate a function and modify it depending on the exceptions.

I leave an example

element_append($('head'),$('#edit-tipo-documento'),'<meta name="TagAutomataAccion1" content="home">',false,null);
element_append($('head'),$('.linea_restablecer'),'<meta name="TagAutomataAccion1" content="restablecer contraseña">',false,null);
element_append($('meta[name=TagAutomataAccion1]'),'homeCampaña',true,"content");

function element_append(item,element,html_string,is_attr,content_type){

if(element.exists()){
    if(is_attr){
    item.attr(content_type,html_string);
  } else {
    item.append(html_string);
  }     
}
}

It is not advisable if you are going to have many exceptions.

    
answered by 11.08.2017 в 17:29