jQuery使用click()赋值变量

jQuery assigning a variable with click()

本文关键字:赋值 变量 使用 click jQuery      更新时间:2023-09-26

我有一个简单的函数,用户可以在其中单击div,该div包含一个值属性,该属性是一个唯一的URL,然后我的jQuery应该读取该属性,并根据该唯一的URL发出ajax请求。

$("#user_result").click(function(){         
    var loadUrl = $(this).attr("value");
    $("#user_profile").html(ajax_load).load(loadUrl);
});

它适用于我列表中的第一个元素,其中value="{{URL}}"属性位于div#user_result:中

<div id="user_result" onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" value="{% url accounts.views.quickview user.user %}">
    <div id="user_thumbnail">
            <img height="50px" width="50px" src="/static/{%if user.thumbnail %}{{user.thumbnail}}{%else%}cms/images/profile_default.png{%endif%}"> 
    </div>
    <div id="user_teaser">
        <span id="fullname">{{user.fullname}}</span>
        <span id="title"> {{user.title}} </span>
    </div>
</div>

但它对我点击的任何其他元素都不起作用。

如何确保每次单击var时都能继续为其分配一个新值?

div id必须是唯一的,所以将jquery更改为

$(".user_result").click(function(){         
    var loadUrl = $(this).attr("title");
    $("#user_profile").html(ajax_load).load(loadUrl);
    }); 

并将您的id转换为类

   <div class="user_result" onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" title="{% url accounts.views.quickview user.user %}">
        <div class="user_thumbnail">
                <img height="50px" width="50px" src="/static/{%if user.thumbnail %}{{user.thumbnail}}{%else%}cms/images/profile_default.png{%endif%}"> 
        </div>
        <div class="user_teaser">
            <span class="fullname">{{user.fullname}}</span>
            <span class="title"> {{user.title}} </span>
        </div>
</div>
<div class="user_result" onmouseover="ChangeColor(this, true);" onmouseout="ChangeColor(this, false);" title="{% url accounts.views.quickview user.user %}">
        <div class="user_thumbnail">
                <img height="50px" width="50px" src="/static/{%if user.thumbnail %}{{user.thumbnail}}{%else%}cms/images/profile_default.png{%endif%}"> 
        </div>
        <div class="user_teaser">
            <span class="fullname">{{user.fullname}}</span>
            <span class="title"> {{user.title}} </span>
        </div>
</div>

也不要期望对div上的属性值的调用总是能正常工作,这不是标准的html,只有表单输入有一个值,我会将其更改为标题(我已经更改了代码示例以匹配

我认为您遇到了这个问题,因为您的div使用的是id而不是类。id在HTML文档中只能使用一次,而类可以使用多次。尝试将您的id更改为类。

user_profile是user_result的父元素吗?

如果是这样,那么当您单击并重新加载该html时,事件处理程序将被删除,您将不得不使用livehttp://api.jquery.com/live/

此外,我个人会使用类而不是id来进行点击例如。….

$(".user-profile").live('click', function(){ 
 ...  
});

不是div的有效属性,因此jQuery将无法识别它

您可以设置一个属性"数据值",并使用$(this).data("value") 进行检索

编辑:最新的jQuery 1.6.1版发生了更改

不应使用.attr((和.pr((来获取/设置值。改为使用.val((方法(尽管使用.attr("value","somevalue"(将继续工作,就像1.6之前一样(。
http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

看起来你是上一次jQuery更新的受害者,只有当属性名称为"value"时才会出现。

然而,我的修复建议将保持不变。