在Jquery UI对话框中基于触发器锚点的文本创建动态按钮名称

Create dynamic button names in Jquery UI Dialog based on the trigger anchor's text

本文关键字:创建 文本 动态 按钮 对话框 UI Jquery 触发器      更新时间:2023-09-26

我已经做了一个jquery UI对话框,它的工作,但我需要传递一个标签的值(名称)到jquery的按钮,但一直在寻找和尝试许多不同的东西,没有:(

我得到了什么:

一个标签(由PHP填充的值):

<a href="#" class="name">'.$name.'</a>
Htmldiv:

<div id="name" title="view or send this user a message?"></div>
jquery:

$(document).ready(function() {
  $(function() {
    $( "#name" ).dialog({
      autoOpen: false,
      width: 500,
      show: {
        effect: "fold",
        duration: 500
      },
      hide: {
        effect: "explode",
        duration: 500
      },
      buttons: {
                    //Names need to go here as part of the buttons
        "Send " + $(this).data('name') + " a message": function() {
          $( this ).dialog( "close" );
        },
        "view " + $(this).data('name') + "profile ": function() {
          $( this ).dialog( "close" );
        }
      }
    });
    $( "a.name" ).click(function() {
    //Pass name to form
    $("#name").data('name', $("a#name").text());
    $( "#name" ).dialog( "open" );
  });
});

});

所以我需要从a#name中获取名称,我尝试了。text()。到用于按钮的jquery。

谢谢你的帮助

你在创建对话框时有一些问题,试试这个方法。

在创建按钮时,您正在连接对象属性,这是无效的语法,再加上在初始化期间不存在时试图访问data('name')。相反,在需要的时候创建按钮,即在对话框显示之前,当你点击超链接时,你知道需要添加到按钮上的name是什么。

小提琴

 $(function () { // Same as document ready. only one of them is needed. No need to chain them
    var dial = $("#name").dialog({
        autoOpen: false,
        width: 500,
        show: {
            effect: "fold",
            duration: 500
        },
        hide: {
            effect: "explode",
            duration: 500
        }
    });
   $("a.name").click(function () {
     //Pass name to form
     var name = $(this).text();
     dial.dialog({
        buttons: getButtons(name),
        autoOpen:true
     })
   });
});
function getButtons(name) {
    var dialog_buttons = {}; //Create the buttons here.
    dialog_buttons["Send " + name + " a message"] = buttonCallBack; //set the call back.
    dialog_buttons["view " + name + " profile"] = buttonCallBack; // assign different call back if required
    return dialog_buttons;
}
function buttonCallBack() {
    $(this).dialog("close");
}

您的a标签选择器是错误的。把

$("#name").data('name', $("a#name").text());

$("#name").data('name', $('a.name').text());