0

I am using jQuery hide() function to hide an element in two situations. One is the normal situation and it is working there. The other situation is that the part that contains the element is loaded through AJAX. I have written the script in the page to which the content is loaded to. But in this case, the function is not working. I have given the function in onclick. The click is triggered, but it is not hiding the element. As the click is triggered, I think there is no need to use live()

My element code is as follows :

<input type="button" onclick="addMoreElements(this.id);" value="Add" id="406" class="button">

and in the addMoreElements function I have

function addMoreElements(currentElement){
        $('#406').hide();
}
4

3 回答 3

1

如果您观察到您正在将 this.id 传递给您的 javascript 函数并明确使用 $("#406") 。相反,你可以试试这个

function addMoreElements(currentelement){
    $("#"+currentelement).hide();
}

希望这可以帮助。

于 2012-12-13T08:13:24.557 回答
0

尝试这个:

HTML

<input type="button" value="Add" id="406" class="button" />​

jQuery

$('#406').on('click', function() {
    $(this).hide();
})​
于 2012-12-13T08:08:01.823 回答
0

我尝试了您的代码,请尝试在 html 元素之前定义您的 javascript。那应该这样做。

示例代码:

 <script type="text/javascript">

    function addMoreElements(){
          $("#406").hide();     
    }
</script>

<input type="button" onclick="addMoreElements();" value="Add" id="406" class="button" />

这背后的原因是,当浏览器看到设置了事件处理程序属性的元素时,浏览器会立即检查函数指针,如果还没有定义函数,那么即使定义了函数,事件也不会被正确处理,因此,当您使用属性事件处理程序时,请确保您包含所有使用过的函数,这些函数要么在 head 标签中定义,要么包含在 head 标签中。

或者只是在页面加载后使用 jquery 的事件绑定器,如下所示:

$(document).ready(function(){
   $(".element").click(function(){
      //do something with the element by using $(this)
    });

});

于 2012-12-13T08:09:47.763 回答