jquery动态添加和删除元素 [英] Jquery adding and removing elements dynamically

查看:90
本文介绍了jquery动态添加和删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图动态添加和移除span元素。它抛出语法错误,如

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


预期')'和预期';'

expected ')' and expected ';'

请帮我解决。

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


推荐答案

您有两个问题。首先,您需要使用不同的引号将字符串分隔到您在字符串中使用的字符串。有用的是,在JS中,您可以使用单个(')或双()引号来实现相同的目的。此外,属性不应该有一个尾随; 。使用具有语法的文本编辑器会很有帮助突出显示因为它几乎不可能错过这样的错误。

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.

你的第二个问题是 remove()方法需要一个选择器,而不是整个HTML字符串。要删除附加在焦点事件中的 span ,请使用 next()选择它,然后 remove()。试试这个:

Your second problem is that the remove() method expects a selector, not a whole HTML string. To remove the span which was appended in the focus event, use next() to select it, then 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();
});

最后,请注意很多更好的做法来定义你的风格CSS,因为它将HTML / JS从样式规则中分离出来,并且有助于缩短JS。试试这个:

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. 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();
});

工作示例

这篇关于jquery动态添加和删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆