简体   繁体   English

jQuery的点击行为有所不同

[英]jQuery on click behaves differently

I am generating html elements according to some condition i receive from server response. 我正在根据服务器响应收到的某些条件生成html元素。

@if($candidate->status == "new")
   @if($candidate->priority == "")
   <a id = "prioritize" data-value = "{{$candidate->id}}" ><img id = "priority" src="icons/non_priority.png"></img></a>
   @else if($candidate->priority == "yes")
   <a id = "prioritize" data-value = "{{$candidate->id}}" ><img id = "priority" src="icons/priority.png"></img></a>
   @endif 
@endif

and few more like this with same inner if conditions 还有更多这样的情况,如果条件相同

@if($candidate->status == "scheduled")
@endif

@if($candidate->status == "good")
@endif

@if($candidate->status == "bad")
@endif

The on click function works only on elements that are populated when "new" condtion is satisfied. on click功能仅对满足“新”条件时填充的元素起作用。

@if($candidate->status == "new")
@endif

and doesn't work on other elements that are populated by other conditions. 并且不适用于由其他条件填充的其他元素。 But when i comment of new condition. 但是当我评论new情况时。 Someother condition like " good " or " bad " or " scheduled " works. 诸如“ ”或“ ”或“ 预定 ”之类的其他条件也可以工作。

$(document).ready(function(){

$('#favorite').on('click',function(){
    if ($(this).find('img').attr('src','icons/non_star.png')) {

            var candidate_id = $(this).data('value');
            alert(candidate_id);
    }
});

$('#prioritize').on('click',function(){
    if ($(this).find('img').attr('src','icons/non_priority.png')) {

            var candidate_id = $(this).data('value');
            alert(candidate_id);
    }
});

});

I don't understand the issue behind this though all the id's clicked are same. 尽管所有ID均被点击,但我不了解其背后的问题。

An html id is unique. html ID是唯一的。 You should use à class attribute. 您应该使用àclass属性。 Change id by class and in your jquery change #id by .class. 按类更改ID,并在您的jquery中按.class更改#id。

.attr( attributeName, value ) is used to set attribute value and not test her. .attr(attributeName,value)用于设置属性值,而不是对其进行测试。 Use .attr(attributeName) === 'value' You can also add data-* attribute to this test for a solution more sure. 使用.attr(attributeName)==='值'您也可以在此测试中添加data- *属性以获得更确定的解决方案。

You have to use class for html elements that can appear multiple times because id s are always unique for html elements. 您必须对可能多次出现的html元素使用class ,因为id始终对于html元素而言是唯一的。 Add class and change your code as below 添加类并按如下所示更改代码

$('.favorite').on('click',function(){
if ($(this).find('img').attr('src','icons/non_star.png')) {

        var candidate_id = $(this).data('value');
        alert(candidate_id);
}
  });

我认为您应该根据元素的状态为元素赋予不同的ID,或者使用它们的类名来调用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM