仅当jQuery中的div为空时如何附加html? [英] How to append html only if the div is empty in jQuery?

查看:106
本文介绍了仅当jQuery中的div为空时如何附加html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码可在PHP文件中显示用于登录和注册的内容:

I have this code for displaying content for login and registration in my PHP file:

<?php // LOGIN PART ?>
<div class="login-part"></div>

<?php // REGISTRATION PART ?>
<div class="registration-part"></div>

这在我的js文件中:

$(document).ready( function() {
            // FOR REGISTRATION
            $('span.logreg.reg').click(function () {

                $('div.registration-part').append('<p>Registration</p>');
            });

            // FOR LOGIN
            $('span.logreg.log').click(function () {

                // insert html
                $('div.login-part').append('<p>Login</p>');
            });
        });

现在,每次我单击一个范围时,都会根据单击的范围显示文本登录或注册.

Now, everytime I click on a span it shows the text login or registration, according to which of the span was clicked.

没关系,但是我只需要添加一次,因此当用户在跨度上单击更多次时,就不会添加更多文本.

Thats OK, however I need to add it only once, so when the user click more times on the span it will be not adding more text.

Remove()或empty()不是一个选项,因为我需要输入框内的信息(稍后将有输入框用于插入用户信息)留在此处,并且如果用户再次不小心单击了跨度.

Remove() or empty() is not an option, as far as I know, because I need the information inside input boxes (there will be input boxes later for inserting user info) to stay there and not be deleted if the user click accidentally on the span again.

但是,如果他单击另一个跨度,它可以删除div内的html.例如.如果span.log处于活动状态,则在单击span.log之后没有任何反应,但是如果他单击span.reg,则div.login-part内部的html将被删除,并显示注册文本.

It can however delete the html inside the div, if he clicks on another span. E.g. if span.log is active, after clicking on span.log nothing happens, but if he clicks on span.reg the html inside div.login-part will be removed and registration text will appear.

如何做这样的事情?

推荐答案

请尝试APi:.one:(阅读您的问题似乎只需要使用.one附加一次像login这样的HTML就可以解决此问题.问题)

Try APi: .one please : (Reading your question it seems you only need to append the HTML like login once using .one will resolve this issue)

将处理程序附加到元素的事件.处理程序被执行 每个元素最多一次.

Attach a handler to an event for the elements. The handler is executed at most once per element.

APi链接: http://api.jquery.com/one/

通过这种方式,追加仅会根据需要进行一次,并且您不会有重复的html显示多次.

This way append will only one time as desired and you will not have duplicate html showing multiple times.

希望这会有所帮助,请让我知道我是否错过了任何事情,

Hope this helps, please lemme know if I missed anything,

更多位差异演示: http://jsfiddle.net/avSDa/9 /使用适合您的.is(:empty).

further bit diff demo: http://jsfiddle.net/avSDa/9/ using .is(:empty) which ever suits you.

代码是这样的

  $('span.logreg.log').one('click', function () {

                // insert html
                $('div.registration-part').append('<p>Login</p>');
            });

这篇关于仅当jQuery中的div为空时如何附加html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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