You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Kendo下拉列表选中值在页面显示对应自定义文本?

问题

我页面上有如下Kendo DropDownList控件,已绑定onChange事件,且能在事件中获取选中项的文本:

@(Html.Kendo().DropDownList()
                .Name("Awards")
                .Label(label => label.Content("Please select Award type from the list. "))
                .DataTextField("AwardCategory1")
                .DataValueField("AwardId")
                .OptionLabel("Select award")
                
                .DataSource(source =>
                {
                    source.Read(read =>
                    {
                        read.Action("GetAwards", "Home");
                    });
                })
              .Events(e => e.Change("onChange"))
            )

我的onChange事件代码如下:

<script>
  function onChange(e) {
         var dropdownlist = $("#Awards").data("kendoDropDownList");
         var text = dropdownlist.text();
         $(".award").text(text);
         alert(text);
    }
</script>

目前已能通过alert看到选中项文本,但希望根据不同选中值显示对应的自定义<h3>文本,例如选中"Award1"时显示<h3>This is the award text for several people. Everyone will be given Award "A"</h3>,选中"Award2"时显示<h3>Test this award. Please make sure, you will be on time</h3>等。

我尝试过以下方案,但发现使用text()方法会导致HTML标签被转义,无法正确显示<h3>格式:

function onChange() {
        var dropdownlist = $("#Awards").data("kendoDropDownList");
        var text = dropdownlist.text();
        //$(".award").text(text);
        const award = {
            "Award1": `<h3>This is the award text for several people. Everyone will be given Award "A"</h3>`,
            "Award2": `<h3>Test this award. Please make sure, you will be on time</h3>`,
            "Award3": `<h3>Blablabla</h3>`,
        }[text]
        $(".test").text(award);
        //return { awardText: text };
    }

页面上已有<div id="test"></div>容器,我不需要Telerik控件相关的帮助,仅需解决JavaScript部分的问题,如何正确显示对应自定义HTML文本?

解决方案

问题核心是你用了jQuery的text()方法——这个方法会把所有内容当作纯文本处理,自动转义HTML标签,导致<h3>被显示成字符串而非渲染成标题。

只需要把text()替换成html()方法即可,html()会解析传入的HTML代码并渲染到页面上。同时注意你页面上的容器是id="test",选择器要对应使用$("#test")(ID选择器用#,类选择器才用.)。修改后的代码如下:

function onChange() {
    var dropdownlist = $("#Awards").data("kendoDropDownList");
    var text = dropdownlist.text();
    const awardContent = {
        "Award1": `<h3>This is the award text for several people. Everyone will be given Award "A"</h3>`,
        "Award2": `<h3>Test this award. Please make sure, you will be on time</h3>`,
        "Award3": `<h3>Blablabla</h3>`
    }[text];
    
    // 用html()渲染HTML内容,同时处理未匹配到选项的情况,避免显示undefined
    $("#test").html(awardContent || "");
}

内容的提问来源于stack exchange,提问作者rimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 22:13:24