I'm building a jQuery script, and I have problems understanding how everything works, so basically I'm going to create a function instead of rewriting a lot of code, so this is how I've done it:
$('.chkboxes').on("change", ":checkbox", function () {
if (this.checked) {
var yolo = this.id;
switch(yolo) {
case "chkBox1":
break;
case "chkBox2":
addfield("yolo" , "yolo", "text", "yolo");
break;
}
}
and then I have a function named "addfield":
function addfield(class, name, type, id) {
var fieldstring = '<tr class=" ' + class + '"><td>' + name + '</td><td><input type="' + type + '" id="' + id + '" name ="' + name + '" /></td></tr>';
alert(fieldstring);
$(fieldstring).hide().appendTo(wrapper).fadeIn(999);
}
But I don't get it to work, how should I do this, I keep seeing functions as java methods but it doesn't work the way I want it to work! Any help is appreciated!
You are not allowed to use keywords like class
, var
, new
, etc. in variable names, so you should change your
function addfield(class, name, type, id) {
var fieldstring = '<tr class=" ' + class + '"><td>' + name + '</td><td><input type="' + type + '" id="' + id + '" name ="' + name + '" /></td></tr>';
alert(fieldstring);
$(fieldstring).hide().appendTo(wrapper).fadeIn(999);
}
to
function addfield(someArgRepresentsClass, name, type, id) {
var fieldstring = '<tr class=" ' + someArgRepresentsClass + '"><td>' + name + '</td><td><input type="' + type + '" id="' + id + '" name ="' + name + '" /></td></tr>';
alert(fieldstring);
$(fieldstring).hide().appendTo(wrapper).fadeIn(999);
}
By "use in variable names" i mean make the keyword variable name. You can write smth like newClass
etc.
$('.chkboxes').on("change", ":checkbox", function () {
var $this = $(this);
if ($this.is(':checked')) {
var yolo = $this.attr('id');
if (yolo == "chkBox1"){
break;
} else if (yolo == "chkBox2"){
addfield("yolo" , "yolo", "text", "yolo");
break;
}
}
}
The second one is this.id
, change it to $(this).attr('id')
And btw, don't use switch, in such cases, if().. else
would be muuuch better.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.