繁体   English   中英

如何在下拉列表中获取所选值 <div><p> 使用点击事件的jQuery?

[英]How to get the selected value on a Dropdown of <div> <p> using JQuery by click event?

我有一个下拉月份,它会根据所选的年份动态填充。

在此处输入图片说明

当用户单击月份下拉列表时,将显示月份列表。 用户如何使用JQuery获得选定的月份值? 假设下拉列表是动态填充的。

当用户单击显示的月份列表时,将调用此函数

$("#month").click(function() {
    var value = $(this).children("div p").val(); // return undefined
    console.log("month: " + value);
}); 

HTLM下拉菜单

<div id="month">
    <span class="input">März</span>
    <div class="dropdown">
        <p></p>
    </div>
</div>

当用户单击下拉列表月时,将调用UpdateMonths()函数并动态填充列表

$("#month span").click(function(event) {

    $("#month div").html(UpdateMonths());


    event.stopPropagation();
    if (!$(this).hasClass('disabled')) { // only open downdown when not disabled
        Dropdown($(this).parent().attr("id"));
    } else Dropdown(); // hide all dropdown menues
});

function Dropdown (element) {

    $("#month div").hide(); // hide all dropdowns
    if (element) $("#"+element+" div").toggle(); // show dropdown of specified element
}

这就是我填写清单的方式

function UpdateMonths(){
var temp = "";
    if (parseInt(Get.Year()) <= 2012){
        for (var i = 0; i < Get.Months.length; i++) {
            var monthsChain = "<p>"+Get.Months[i]+"</p>";
            temp += monthsChain;
        };
    }else{
        temp = "<p>Januar</p><p>Februar</p><p>März<p></p><p>April</p><p>Mai</p><p>Juni</p><p>Juli</p>"; 
    }
    return temp;
}

你可以试试

var value = $(this).find("div p").text();

或更具体:

var value = $(this).find("div.dropdown p").text();

.val()用于获取表单字段的值。 如果您想要通用HTML元素(例如<span><p>的文本内容,则需要使用.text()

$("#month").click(function() {
    var value = $(this).find('.input').text();
    console.log("month: " + value);
}); 

确保也从下拉菜单的HTML类中删除句点(。)-类必须以字母开头,而不是数字或标点符号。

看起来您选择的值在<span>而不是<p> ,因此应为:

var value = $(this).children("span.input").text();

编辑:您可以这样做:

$(document).on('click', '#month', function(e) {
    if($(e.target).is('p')) {
        var value = $(e.target).text();
        console.log(value);
    }
}); 

我假设您想从p元素列表中选择月份。

HTML(类似的结构)

<div id="month">
    <span class="input"></span>
    <div class="dropdown">
        <p>January</p><p>February</p>
    </div>
</div>

<div id="year">
    <span class="input"></span>
    <div class="dropdown">
        <p>2013</p><p>2014</p>
    </div>
</div>

jQuery,需要委托事件,因为<p>元素是动态生成的。

$("#month, #year").on('click', '.dropdown p', function() {
    var value = $(this).text();
    console.log("month: " + value);
}); 

如何设置跨度的月份值(在上述范围内)

$(this).parent().siblings('span').text(value);

和jsfiddle一起玩

http://jsfiddle.net/2nuhw/4/

您可以将val()用于输入字段。 使用text()获取文本字段。 平时

并有文字。

尝试这样:

var value = $(this).children("div p").text();

要么

var value = $(this).children("div p").html();

使用html()您可以获得属于span或p标签的任何类型的值。

暂无
暂无

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

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