使用 jquery 添加和删除属性 [英] Add and remove attribute with jquery

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

问题描述

这是我的按钮:

<button id="add">Add</button>
<button id="remove">Remove</button>

这是我的 JavaScript 代码:

this is my JavaScript code:

<script type="text/javascript">
    $(document).ready(function(){   
        /*** Add attribute ***/
        $("#add").click(function(){
            $("#page_navigation1").attr("id","page_navigation1");
        });     
        /*** Remove attribute ***/
        $("#remove").click(function(){
            $("#page_navigation1").removeAttr("id");
        });     
    });
</script>

这是我的html代码:

and this is my html code:

<div id="page_navigation1">next</div>

我的问题是,当我点击删除按钮时,一切都很好,ID 将被删除,但是点击删除按钮后,当我点击添加按钮时,代码不起作用,没有任何反应!

My problem is, when I click on Remove button everything is fine and ID will be removed, but after click on remove button, when I click on Add button, code is not working and nothing happens!

我需要使用此代码添加和删除 ID,但我只能删除 ID,我无法添加 ID.我需要一些帮助,还有一件事,

I need to add and remove ID whith this code, but I can just Remove ID, I cant add ID. I need some help for this, and one more thing,

当按钮处于活动状态时,如何为按钮添加 CSS 样式?像这样,当我单击删除按钮时,我想将按钮背景更改为红色.当按钮处于活动状态时,我需要添加 css 类以添加和删除!我不知道怎么做!

How I can add CSS style for button when button is Active? like this, when I click on Remove button, I want change button background to red. I need to add css class for add and remove when buttons are active! and I dont know how!

推荐答案

这是因为您删除了 id,这就是您查找元素的方式.这行代码试图将 id="page_navigation1" 添加到具有 id 名为 page_navigation1 的元素中,但它不存在(因为你删除了属性):

It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

$("#page_navigation1").attr("id","page_navigation1");

演示:

如果您想添加和删除使您的 <div> 变为红色的类,请使用:

If you want to add and remove a class that makes your <div> red use:

$( '#page_navigation1' ).addClass( 'red-class' );

还有:

$( '#page_navigation1' ).removeClass( 'red-class' );

red-class 是:

.red-class {
    background-color: red;
}

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

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