简体   繁体   English

jQuery动态添加和删除元素

[英]Jquery adding and removing elements dynamically

I am trying to add and remove a span element dynamically. 我正在尝试动态添加和删除span元素。 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>

The way that you are concatenating the values in your HTML string is wrong, 您串联HTML字符串中的值的方式是错误的,

.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" . 要解决这个问题,要么你可以使用single quote在字符串用双引号包裹或尝试使用转义双引号\\"avi\\"s code is wrong"

On top of all, the best approach would be creating element by using jquery, 最重要的是,最好的方法是使用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, 您使用错误的.remove()方法,

$("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. 您必须从$(this)对象中选择相关元素,然后调用remove。


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) 而完成任务的最佳方法是,通过使用相关选择器编写规则,将要完成的样式设计工作分配给CSS(@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, 而js将是,

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 演示

You have two issues. 你有两个问题。 Firstly you need to use different quotes to delimit the string to those you use within the string. 首先,您需要使用不同的引号将字符串定界为您在字符串中使用的引号。 Helpfully, in JS you can use either single ( ' ) or double ( " ) quotes to achieve the same purpose. Also, the class attribute should not have a trailing ; . It can be helpful to use a text editor which has syntax highlighting as it makes it nearly impossible to miss mistakes like that. 有用的是,在JS中,您可以使用单引号( ' )或双引号( " )来达到相同的目的。此外, class属性不应带有尾部;使用文本编辑器时语法高亮显示为:这样几乎不可能错过这样的错误。

Your second problem is that the remove() method expects a selector, not a whole HTML string. 您的第二个问题是remove()方法需要选择器,而不是整个HTML字符串。 To remove the span which was appended in the focus event, use next() to select it, then remove() . 要删除附加在focus事件中的span ,请使用next()选择它,然后使用remove() Try this: 尝试这个:

$("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' }).next('span').remove();
});

Finally, note that it is much better practice to define your styles in CSS as it separates the HTML/JS from the styling rules, and helps make the JS shorter as well. 最后,需要注意的是更好的做法在CSS来定义你的风格,因为它的HTML / JS从样式规则分离,并有助于使JS也短。 Try this: 尝试这个:

input[data-required='true'] {
    background-color: white; /* transparent may work here too */
}
input[data-required='true']:focus {
    background-color: red;
}
span.label_error {
    color: red;
    font-size: 10pt;
}
$("input[data-required='true']").focus(function () {
    $(this).after('<span class="label_error">This field is required</span>');
}).blur(function () {
    $(this).next('span').remove();
});

Working example 工作实例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM