如何在单击链接/过滤器的基础上向onclick函数添加字符串?

How can you add a string to an onclick function based on a link/filter clicked?

本文关键字:onclick 函数 添加 字符串 基础上 单击 链接 过滤器      更新时间:2023-09-26

希望使用jQuery或js.

我有过滤器可以改变页面的显示方式。我正在跟踪通过使用锚标记上的onclick过滤的图像上的点击。我想传递的链接/过滤器被选中与文本一起,我目前住房在onClick.

我有过滤器和trackLink工作。我只需要将数据过滤器值附加到锚标记中的onclick。

这是一个例子来照亮这个情况…

过滤器
<a href="#" data-filter=".optionone">Option One</a>
<a href="#" data-filter=".optiontwo">Option Two</a>

内容被过滤-同一页面

<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want')" href="1.aspx">
        <img src="1.jpg" alt="1" />
        <div>Test</div>
    </a>
</div>  
<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want')" href="2.aspx">
        <img src="2.jpg" alt="2" />
        <div>Test</div>
    </a>
</div>  

我想要的-传递数据过滤器的值

<div class="item">
    <a onclick="trackLink('Text I Want', 'Text I want' + the filter name as it is being click passed)" href="1.aspx">
        <img src="1.jpg" alt="1" />
        <div>Test</div>
    </a>
</div>   

不能在HTML元素的函数中添加这样的文本。

我要做的是通过在过滤器中添加一个类来切换HTML,并将"Text I want"移动到它们自己的数据值:

<a href="#" class="filter" data-filter=".optionone">Option One</a>
<a href="#" class="filter" data-filter=".optiontwo">Option Two</a>
...
<div class="item"><a data-first-text="Text I Want" data-second-text="Text I want" href="1.aspx"><img src="1.jpg" alt="1" /><div>Test</div></a></div>

然后使用jQuery调用你的函数:

var filter_text;
$('a.filter').click(function(event) {
    // set the filter text to whatever the filter is
    filter_text = $(this).data('filter');
});
$('.item a').click(function(event) {
    var first_text = $(this).data('first-text');
    var second_text = $(this).data('second-text');
    // call trackLink with your desired texts
    trackLink(first_text, second_text + filter_text);
});

小提琴

在JQuery中,您可以使用如下代码:这里演示

$('a').click(function(){
alert($(this).attr('data-filter'));
});

我建议你这样做:

$(".item a").click(function () {
    var value = $(this).attr("data-filter"); // 'this' = the a element being clicked
    trackLink('text you want', 'text you want' + value);
});

最后从你的onClick中删除trackLink函数,甚至在a标签

在你的文档头部包含jQuery

<script src="http://code.jquery.com/jquery-latest.js"></script>

然后,创建一个全局函数,像这样:

jQuery.noConflict();
jQuery(document).ready(function($){
    getDataFilter = function(selector){
        return $(selector).attr("data-filter");
    }
    anotherFunction = function(dataFilter){
        // do something
    }
});

你的标签看起来像这样

onclick="anotherFunction(getDataFilter('.item a'));"

或者如果你想要一个纯javascript的解决方案:

document.querySelector('.item a').getAttribute("data-filter");

希望有帮助!