skip to Main Content

I apologize in advance, but I don’t speak English.
After loading the code and clicking on TEST, the Data-filter function starts, but after another click, the function does not start anymore. I would need the Data-filter to activate after every click. Some ideas? And thanks in advance for your help.

Here is my test code.

<div class="test"></div>
<script>
const code = document.querySelector(".test");
function test(test1, test2) {
let Text = "";
Text += `<a href="#" class="number" data-filter=".text" onClick="test(1, 1)">Test</a>`;
Text += `<a href="#" class="number" data-filter=".text1" onClick="test(1, 1)">Test1</a>`;
code.innerHTML = Text;

}
test(1, 1);
$('a').click(function(){
alert($(this).attr("data-filter"));
})
</script>

codepen

2

Answers


  1. Chosen as BEST ANSWER

    Thanks for the responses. I thought only a simple solution was enough and it was enough for this function. So how should I adapt the code so that the Data-filter works outside of javascript? I would like to preserve the structure of the js code.

    Text += `<a href="#" class="number" data-filter=".text" onClick="test(1, 1)">Test</a>`;
    
    
        <div class="text">Text</div>
        <div class="text1">Text</div>
    <script>
        function test(test1, test2) {
            let Text = "";
            Text += `<a href="#" class="number" data-filter=".text" onClick="test(1, 1)">Test</a> `;
            Text += ` <a href="#" class="number" data-filter=".text1" onClick="test(1, 1)">Test1</a>`;
            code.innerHTML = Text;
        }
    

  2. The event handlers are lost when the test div is written by the test function

    If you want to add the event handling back in, you could move the event handling code inside your test function after rewriting the contents of the test div:

    function test(test1, test2) {
        let Text = "";
        Text += `<a href="#" class="number" data-filter=".text" onClick="test(1, 1)">Test</a> `;
        Text += ` <a href="#" class="number" data-filter=".text1" onClick="test(1, 1)">Test1</a>`;
        code.innerHTML = Text;
    $('a').click(function(){
        alert($(this).attr("data-filter"));
      alert("lol");
    })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search