在javascript中将硬代码参数更改为动态参数
在我们当前的示例中,为了使expand函数工作,我们需要在javascript中硬编码id expand_product_images_xxxx,以便它能够触发函数。备注:我在程序中使用的是jquerymobile 1.3.2 e、 g.点击测试在javascript中将硬代码参数更改为动态参数,javascript,php,Javascript,Php,在我们当前的示例中,为了使expand函数工作,我们需要在javascript中硬编码id expand_product_images_xxxx,以便它能够触发函数。备注:我在程序中使用的是jquerymobile 1.3.2 e、 g.点击测试 <a href="" id="expand_product_images_2978">Test</a> 您可以添加一个函数并发送在html中单击的对象id,如下所示: <a href="javascript:;"
<a href="" id="expand_product_images_2978">Test</a>
您可以添加一个函数并发送在html中单击的对象id,如下所示:
<a href="javascript:;" id="expand_product_images_2978" onclick="expandFunc(this.id)">Test</a>
<div data-role="collapsible" id="selection_product_estate_images_2978">
您可以使用如下参数编写函数:
function expand(id) {
$("#selection_product_images_"+id).trigger("expand");
}
并在链接的onclick事件中调用此函数,例如,假设您正在使用php标签中的php:
<a href="" id="expand_product_images_2978" onclick="expand(<?php echo $id; ?>)">Test</a>
您可以将所需类id的选择器嵌套到要展开的元素中,然后使用jQuery处理它们。下面的代码可以更好地解释这一点 考虑到您有以下html,我会这样做: HTML
此处提供的演示:由于我使用的是jquerymobile,而不是onclick=,它是否可以对齐使用id=expand\u product\u image\u xxxx的jquerymobile格式?顺便说一句,如果我有几个这样的选项卡,比如selection\u product\u estate\u images\u,selection\u product\u estate\u info\u,selection\u product\u estate\u details\u,等等。完善上述代码的最简单方法是什么?顺便说一句,如果我使用我的原始代码,当我点击它时,选项卡会高亮显示。但是,当我按照建议使用代码时,它不会突出显示。您可能会从中看到差异,再次感谢您的善意帮助!所以每个标签都有一个可扩展的,对吗?然后,您需要选项卡和可展开表之间的映射,或者选项卡和可展开表之间的模式。这里有一个映射示例:这里有一个命名模式示例-缺点:您需要严格遵守命名约定:太棒了!这非常有帮助!再次感谢你的帮助!由于我使用的是jquerymobile,而不是onclick=,它是否可以对齐使用id=expand\u product\u image\u xxxx的jquerymobile格式?您可以将onclick与jquery mobile一起使用。只需确保将rel=external添加到对象中。
function expandFunc(id)
{
var idArr = id.split("_");
var realId = idArr[idArr.length-1];
$("#selection_product_estate_images_" + realId ).trigger("expand");
}
function expand(id) {
$("#selection_product_images_"+id).trigger("expand");
}
<a href="" id="expand_product_images_2978" onclick="expand(<?php echo $id; ?>)">Test</a>
<div>
<a href="" id="expand_product_images_2978">Test 1</a>
<div data-role="collapsible" id="selection_product_estate_images_2978"></div>
</div>
<div>
<a href="" id="expand_product_images_2979">Test 2</a>
<div data-role="collapsible" id="selection_product_estate_images_2979"></div>
</div>
<div>
<a href="" id="expand_product_images_2980">Test 3</a>
<div data-role="collapsible" id="selection_product_estate_images_2980"></div>
</div>
<div>
<a href="" id="expand_product_images_2981">Test 4</a>
<div data-role="collapsible" id="selection_product_estate_images_2981"></div>
</div>
var expand = function(event){
// the link element
var $a = $(this);
// link id
var id = $a.attr('id');
// get the uid form link id
var uid = id.replace( /^\D+/g, '');
// get the colapsable element
var $colapsable = $('#selection_product_estate_images_'+uid);
$colapsable.trigger('expand');
// stop event propagation
event.preventDefault();
return false;
};
// Attach on click events on links
$('a[id*="expand_product_images_"]').on('click', expand);