5

I'm currently working on a web application using HTML 5, CSS and JQuery. I have an unordered list (ul) for displaying page links, with each li element containing the page link. This list is created dynamically using jQuery.

What I would like to do is to have the list elements display only the page name in the link, but at the same time retain the full link path. For example, "http://www.foo.com/xyz/contactus" would be displayed as "contactus", but the li element would still "know" the full link path. For this purpose the value attribute of li would have been perfect, since i could set them like this:

var ul = $('<ul/>').attr('id', 'linkList');
for (var i = 0; i < linksOnPage.length; i++)  // linksOnPage is an array with all the links
    {
        var pgName = linksOnPage[i].toString().slice(steps[i].toString().lastIndexOf('/') + 1);

        // Create list element and append content
        var li = $('<li/>').text(pgName);    // Set the text to the page name
        li.attr('value', linksOnPage[i].toString());    // Set the value to the full link

        ul.append(li);
    }

This would create a list like:

<ul>
    <li value="http://www.foo.com/xyz/contactus">contactus</li>
    ...
</ul>

Unfortunately the value attribute of li has been deprecated since HTML 4.01 (anyone know the rationale behind this? Seems pretty useful to me...).

So, I would like some advice on how to proceed. One option is to ignore the deprecation and use the value attribute anyway, since all the major browsers still support it, but I'm not very keen on using a deprecated feature and it just feels wrong.

Any ideas?

4

3 回答 3

10

更改自:

<li value="http://www.foo.com/xyz/contactus">contactus</li>

至:

<li data-value="http://www.foo.com/xyz/contactus">contactus</li>

data-*模式是在 DOM 元素中保存值的新 HTML5 方式。

您可以通过以下两种方式之一获取值:

$('#li-Id').data('value');
$('#li-Id').attr('data-value');

您可以阅读有关这些属性的 John Resig 的这篇博文。

jQuerydata函数

于 2012-05-24T07:24:29.667 回答
3

只需使用一个data属性(介绍更长的教程规范):

<li data-path="http://www.foo.com/xyz/contactus">contactus</li>

另外,jQuery 通过该.data方法可以方便地检测和公开这些属性的值。

于 2012-05-24T07:24:24.033 回答
1

即使value已弃用,它仍然可以通过 JavaScript 使用和访问。你只是放弃验证状态!

或者,您可以使用data-*属性(正如我看到其他人所建议的那样)或将值直接映射到 DOM 元素 - 因为您在运行时生成此标记,所以您可以像这样添加一个属性(JS 允许您这样做既是一种祝福和诅咒):

li.someLinkPath = 'some url here';
//and in the click handler you could access this as
this.someLinkPath;

仍然......如果您打算将其用于导航,为什么不使用带有 href 的锚点?

于 2012-05-24T07:31:45.640 回答