CSS Uncaught TypeError:无法读取属性' setAttribute'为null

时间:2017-10-19 09:12:19

标签: javascript jquery css css3

我正在尝试给予margin-top:10px到id download-csv

这是html和javascrpit:

// Create empty list of type CustomClass
List<CustomClass> comboBoxDataSource = new List<CustomClass>();

// Create a property for the selected item
CustomClass CurrentSelectedItem { get; set; }

// Use external function to fill the list with some data
LoadDataAndInsertIntoList(comboBoxDataSource);

// Set datasource, display- and value-member
cboComboBox.DataSource = comboBoxDataSource;
cboComboBox.DisplayMember = "DisplayName";
cboComboBox.ValueMember = "Value";

private void cboComboBox_SelectionChangeCommitted(object sender, EventArgs e)
{
   // What happens here, if using DropDownStyle.DropDown and 
   // a custom text is entered, instead of the predefined options?
   CurrentSelectedItem = (CustomClass)cboComboBox.SelectedItem;
}

它抛出错误    TypeError:无法读取属性&#39; setAttribute&#39;为null

3 个答案:

答案 0 :(得分:4)

您需要确保在JS代码访问这些元素之前加载标记。

此外,您无法将margin提供给inline个元素,将display 样式属性设置为display-inline

&#13;
&#13;
var download_csv = document.getElementById("download-csv");
var count_layer = 1;
if (count_layer == 1) {
  download_csv.style.marginTop = "10px";
} else {
  download_csv.style.marginTop = "50px";
}
&#13;
<span style="display: inline-block;" id="download-csv">
   <input type="submit"   id="csv_download"  value="Download">
</span>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

您可以尝试以下代码:

if(count_layer==1)
        download_csv.style.marginTop = "10px";
}else{
       download_csv.style.marginTop = "20px";
}

答案 2 :(得分:1)

现在您的javascript代码在页面加载之前正在执行,因此<html>属性尚未加载,然后您将收到错误。

要解决此问题,请将您的javascript代码放在$(document).ready

$(document).ready(function() {
    //Your code goes here
}) ;