获取特定元素中的元素


Get an element inside a specific element

我有一个php代码,可以构建这样的html代码:

echo '<button><span class="glyphicon glyphicon-zoom-in afficher_itk" aria-hidden="true"></span></button>';
echo' <div class="itk" id="'.str_replace(' ','',$systeme_culture['nom_plante']).'">
    <table class="table">
        <th><td>
            <tr colspan="2">
                   <label>Nom : </label>
                   <input class="nom_itk" id="nom_itk" value="test">
             </td</tr>
        </th>
     </table>
 </div>';

这个代码是动态生成的,我可以有不止一个这样的代码。

由于它可能有几种类似的东西,所以我希望在运行javascript时以rights元素为目标。

当我点击按钮时,我想在相应的input中添加一个内容。不是第一个,不是最后一个,但只在匹配的代码中。

我在js:中有这样的东西

$(".afficher_itk").click(function(){
    $itk = $(this).closest(".itk"); //Here, I tried to select the closest itk class which correspond to the first div
    $itk.find(".nom_itk").val("test"); //Here I tried to search the input child
}

但是这个代码不起作用。有人知道我该怎么做吗?

不要在DOM树中选择最接近的itk,最接近的向上遍历。相反,使用.next从当前元素中选择下一个itk

$(".afficher_itk").click(function(){
    $itk = $(this).next(".itk"); 
    $itk.find(".nom_itk").val("test");
});

我发现了自己的能力。我没有选择closest,而是使用函数parents()获得了td父级。之后,我可以使用find函数。

$itk = $(this).parents('td');
$itk.find('.nom_itk').val("lison");

试试这个:

如果元素是DOM对象,它就会工作

jQuery("html").on("click",".afficher_itk", function(){
    $itk = $(this).next(".itk"); 
    $itk.find(".nom_itk").val("test");
});