根据用户从jQuery UI可选下拉框中选择的内容创建链接

Create a link based on what the user selects from this jQuery UI selectable drop box

本文关键字:选择 链接 创建 用户 jQuery UI      更新时间:2024-03-11

我使用的是:

http://jqueryui.com/demos/selectable/#method-选项

这是我的代码:

<ol id="selectable">
    <?php foreach ($collection as $key=> $word): ?>
    <li class="ui-widget-content"> <?php echo $word ?> </li>
    <?php endforeach ?>
</ol>

如何根据用户的选择创建超链接?每次所有的单词都不一样。

使用selected事件:

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            alert(ui.selected.innerHTML);
        }
    });
});​

ui.selected是所选项目的DOM元素

工作示例

如果在li中添加data属性,并为href添加更多详细信息,则会更容易:

<ol id="selectable">
    <?php foreach ($collection as $key=> $word): ?>
    <li class="ui-widget-content" data-href="<?php echo $href ?>"> <?php echo $word ?> </li>
    <?php endforeach ?>
</ol>

然后

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            alert($(ui.selected).data('href'));
        }
    });
});​

此处的工作示例

要使用所选项目创建链接(锚点),您可以执行以下操作:

$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
            $item = $(ui.selected);
            $href = $item.data('href');
            $text = $item.text();
            $('<a />').attr({
                href: $href
            }).text($text).append('<br />').appendTo('#links');
        }
    });
});​

示例

更新

你可以这样做来存储所选项目,直到它需要为止——即按下按钮:

// create temp variable to store the selected element
var selected;
$(function() {
    $("#selectable").selectable({
        selected: function(event, ui) {
           selected = ui.selected;
        }
    });
    $('#getSel').click(function() {
        // do what you want with the Element here
        alert(selected.innerHTML);
    });
});

此处的工作示例