Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
162 views
in Technique[技术] by (71.8m points)

javascript - Jquery adding and removing elements dynamically

I am trying to add and remove a span element dynamically. it's throwing syntax errors like

expected ')' and expected ';'

please help me to fix it.

<script type="text/javascript">
    $(document).ready(function () {
        $("input[data-required='true']").focus(function () {
            $(this).css({ 'background-color': 'red' }).after("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>");
        });

    $("input[data-required='true']").blur(function () {
        $(this).css({ 'background-color': 'white' }).remove("<span class="label_error;"style="color:red;font-size:10pt">This field is required</span>") ;
    });

    });
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way that you are concatenating the values in your HTML string is wrong,

.after("<span class='label_error' style='color:red;font-size:10pt;'>" +
         "This field is required" +
        "</span>");

To fix this issue either you can use single quote in your string wrapped by double quotes or try to escape the double quote by using like "avi"s code is wrong".

On top of all, the best approach would be creating element by using jquery,

.after($("<span>", {class : 'label_error', 
                    style : 'color:red;font-size:10pt;',
                    text : 'This field is required'
                   }));

This would be more readable and maintainable. And I forgot to spot another one error that you made in your code. You are using .remove() in a wrong way,

$("input[data-required='true']").blur(function () {
   $(this).css({ 'background-color': 'white' }).next("span.label_error").remove();
});

You have to select the relevant element from your $(this) object and invoke remove over it.


And the best approach for finishing up your task is, allot the styling works to be done to the css by writing rules with relevant selectors (said by @rory)

input[data-required='true'] {
  background-color: white;
}
input[data-required='true']:focus {
  background-color: red;
}
span.label_error {
  color: red;
  font-size: 10pt;
}

And the js would be,

var errorMsg = $("<span>", {class: 'label_error',text: 'This field is required'});

$("input[data-required='true']").focus(function() {
  $(this).after(errorMsg);
}).blur(function() {
  $(this).next("span.label_error").remove();
});

DEMO


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...