0

I have the following code

<div id='show_test'></div>

And

var matches = [{
    "category_name": "category_1",
    "stock_name": "stock_1",
    "supplier_stock": "supplier_stock_1"
}, {
    "category_name": "category_2",
    "stock_name": "stock_2",
    "supplier_stock": "supplier_stock_2"
}, {
    "category_name": "category_3",
    "stock_name": "stock_3",
    "supplier_stock": "supplier_stock_3"
}, {
    "category_name": "category_4",
    "stock_name": "stock_4",
    "supplier_stock": "supplier_stock_4"
}];
matches.forEach(function(i, item) {
    var arrayDt = [];
    arrayDt[i, item] = {
        "category_name": this.category_name,
        "stock_name": this.stock_name,
        "supplier_stock": this.supplier_stock
    };
    document.getElementById("show_test").innerHTML += "<div><a id='bt_" + item + "'>click</a></div>";

    document.getElementById("bt_" + item).onclick = function() {
        show_data(i);
    }

    console.log(document.getElementById("bt_" + item));
    console.log(i);

});

function show_data(data) {
    alert(JSON.stringify(data));
}

On the page we show 4 links, when I click on the last link, the script functions as expected. But not the first 3. Why does this not work with the first 3 links?

https://jsfiddle.net/a35wL5ht/

2
  • Welcome to StackOverflow! For this to be a useful question, you’ll need to make it more broadly applicable to questions that other people also ask: check out the guidelines on How to Ask a Good Question. Show what other resources you’ve used, and what you’re hoping to do with this. We’re a community rather than a coding service! Commented Oct 8, 2016 at 0:10
  • Improved formatting, question clarity. Commented Oct 8, 2016 at 6:58

1 Answer 1

1

replace

document.getElementById("show_test").innerHTML += '<div><a href="#" id="bt_' + item + '">click</a></div>';

with

var el = document.createElement("div");
var a =  document.createElement("a");
a.innerHTML = "click";
a.id = "bt_" + item;
el.appendChild(a);
document.getElementById("show_test").appendChild(el);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.