18910140161

JavaScript-如何使按钮独立工作-堆栈溢出

顺晟科技

2022-10-19 12:44:56

159

所以我有了这个表,并在表单元格中添加了一些按钮

<table border="1">

        <tr>
        <th><button id="0" class="mybtn" >1</button><div class="myDiv"></div></th>
        <th><button id="1" class="mybtn">2</button><div class="myDiv"></div></th>
        <th><button id="2" class="mybtn" >3</button><div class="myDiv"></div></th>
    </tr>
    </table>

当我单击按钮时,我希望它们添加一个文本字段。但是当我点击它时,这三个按钮同时工作。

以下是我的jQuery代码

<table border="1">

        <tr>
        <th><button id="0" class="mybtn" >1</button><div class="myDiv"></div></th>
        <th><button id="1" class="mybtn">2</button><div class="myDiv"></div></th>
        <th><button id="2" class="mybtn" >3</button><div class="myDiv"></div></th>
    </tr>
    </table>

如何使按钮独立工作?


顺晟科技:

嗯,您有3个div都具有类“mydiv”,所以如果单击任何按钮,代码都将在这3个div上执行:

要么使用IDs,要么选择父容器,然后使用jQuery$(this)和find()仅在父容器中搜索类为“mydiv”的div。

为每个按钮取同级元素

<table border="1">

        <tr>
        <th><button id="0" class="mybtn" >1</button><div class="myDiv"></div></th>
        <th><button id="1" class="mybtn">2</button><div class="myDiv"></div></th>
        <th><button id="2" class="mybtn" >3</button><div class="myDiv"></div></th>
    </tr>
    </table>

使用。

您所要做的就是使用

<table border="1">

        <tr>
        <th><button id="0" class="mybtn" >1</button><div class="myDiv"></div></th>
        <th><button id="1" class="mybtn">2</button><div class="myDiv"></div></th>
        <th><button id="2" class="mybtn" >3</button><div class="myDiv"></div></th>
    </tr>
    </table>

演示

  • TAG:
相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航