将锚标记属性传递给jquery mobile中的href页面?

时间:2012-11-08 17:37:49

标签: jquery html jquery-mobile

example.html包含:

<a href="mypage.html" data-str="foo">Test</a>

是否可以在data-str内访问mypage.html的值?

3 个答案:

答案 0 :(得分:2)

不,这些值是example.html上html的一部分。

您必须将其作为查询字符串传递才能访问此值。

答案 1 :(得分:0)

这是不可能的,因为@Kami写道......

  

这些值是example.html上的html的一部分

这是绝对正确的,现在我认为你有 2 替代方案来实现你所需要的......

1。使用querystring

2。data-str存储在cookie(使用jQuery在客户端创建),以便在site的其他页面中使用它}。


我更喜欢选项 2 ,这个例子可以帮助你......


使用cookies ...

使用此插件: jquery.cookie

https://raw.github.com/carhartl/jquery-cookie/master/jquery.cookie.js

data-str ...

创建Cookie
//get data attribute
var str = $('.data-to-query').data('str');
//create a cookie called 'data-str' with 'str' variable value
$.cookie('data-str', str);

然后在其他html页面中使用以下内容获取Cookie:

var str = $.cookie('data-str');

//then you can do other things like this...
if(str != null) {
  //do something when cookie value is defined
}

并且,如果您要删除Cookie,只需在您所在的任何html页面执行此操作:

$.cookie('data-str', null);

要知道,很明显,jquery.cookie插件以及jQuery必须在所有html页面中导入。


这就是全部。希望这会有所帮助: - )

答案 2 :(得分:0)

如果您想拥有动态数据属性,但保持引用网址相同,则可以执行以下操作:

HTML

<a href="mypage.html" data-str="foo" class="data-to-query">Test</a>

的jQuery

$('.data-to-query').click(function(){
  window.open($(this).attr('href') + '?str=' + $(this).data('str'),'_self');
  return false;
});
相关问题