Как я могу изменить следующий код, чтобы не использовать eval?

var settings = {};

$(".js-gen-settings").each(function(){
    var date;

    if (($(this).attr("type") === "checkbox") || ($(this).attr("type") === "radio")){//if its a checkbox
        eval("settings."+this.name+" = "+$(this).is(":checked"));
    }else{
        date = $(this).val();
        if (date == ""){
            eval("settings." + this.name + " = null");
        }else{
            eval("settings." + this.name + " = '" + date + "'");
        }
    }
});

JSON.stringify версия settings будет отправлен на сервер с помощью ajax.

3 ответа

Решение

Здесь я перефакторил ваш код:

$( '.js-gen-settings' ).each(function () { 

    if ( $( this ).is( ':checkbox, :radio' ) ) {
        settings[ this.name ] = this.checked;
    } else {
        settings[ this.name ] = this.value ? this.value : null;
    }

});

Если вы хотите динамически изменить свойство объекта, просто введите имя в [скобки],

settings[this.name] = null

settings[this.name] = date;

settings[this.name] = $(this).is(":checked");

Менять:

eval("settings." + this.name + " = null")

в

settings[this.name] = null;

Я уверен, что вы можете выяснить, остальное:)

Другие вопросы по тегам